getline(cin, aString) receiving input without another enter

后端 未结 3 1942
我在风中等你
我在风中等你 2021-01-12 15:31

My code looks like this,

string aString;
cin >> aString;
cout << \"This is what cin gets:\" << aString << endl;
getline(cin, aString)         


        
3条回答
  •  天命终不由人
    2021-01-12 16:37

    "cin >> x" doesn't consume the newline character from the input stream, so the next line you retrieve with getline will contain an empty string. One way to solve this is to use getline to retrieve input line by line and use a stringstream to tokenize each line. After you've extracted all input from the stringstream, the key thing is to call stringstream::clear() to clear the EOF flag set on the stringstream to be able to reuse it later in the code.

    Here's an example:

    #include 
    #include 
    #include 
    
    using namespace std;
    
    int main() {
        string line;
        stringstream ss;
        getline(cin, line);
        ss << line;
        int x, y, z;
        //extract x, y, z and any overflow characters
        ss >> x >> y >> z >> line;
        ss.clear();
        //reuse ss after clearing the eof flag
        getline(cin, line);
        ss << line;
        //extract new fields, then clear, then reuse
        //...
        return 0;
    }
    

    Depending on the length of each input line, getting the whole line at a time and processing it in-memory is probably more efficient than doing console IO on every token you want to extract from the standard input.

提交回复
热议问题