简体   繁体   中英

Repetitive output using cout in CPP

I tried to read a line of string into the program, and when the string is "q" , the program should break, but there were some weird behaviors with my main function. Could you find it out for me?

Thanks a lot!

#include <iostream>
#include <string>

using namespace std;

int main()
{
    int distance;
    int points[1000][2] = {0};
    string input;

    cout << "Please enter the distance: ";
    cin >> distance;
    cin.clear();

    while (true) {
        cout << "Please enter the coordinates, ";
        cout << "enter \"q\" to exit: ";
        getline(cin, input);
        cin.clear();

        // Finish input
        if (input == "q")
            break;
    }

    return 0;
}

And the output in the terminal is:

Please enter the distance: 5
Please enter the coordinates, enter "q" to exit: Please enter the coordinates, enter "q" to exit:

The cout in the while loop seems to have been conducted twice.

The clear function doesn't do what you apparently expect it to do. It clears the streams state flags only.

What you seem to want is probably theignore function to ignore the newline left by the first input operation:

cin >> distance;
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');  // Skip the remainder of the line

Note that you should not call ignore after your getline calls, as the getline function reads the newline as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM