getline() does not work if used after some inputs [duplicate]

混江龙づ霸主 提交于 2019-11-26 17:40:51

问题


Possible Duplicate:
Need help with getline()

getline() is not working, if I use it after some inputs, i.e.

#include<iostream>
using namespace std;

main()
{
string date,time;
char journal[23];


cout<<"Date:\t";
cin>>date;
cout<<"Time:\t";
cin>>time;

cout<<"Journal Entry:\t";
cin.getline(journal,23);


cout<<endl;
system("pause");
}

where as if I use getline() on top of inputs, it does work i.e.

cout<<"Journal Entry:\t";
cin.getline(journal,23);
cout<<"Date:\t";
cin>>date;
cout<<"Time:\t";
cin>>time;

What might be the reason?


回答1:


Characters are extracted until either (n - 1) characters have been extracted or the delimiting character is found (which is delim if this parameter is specified, or '\n' otherwise). The extraction also stops if the end of file is reached in the input sequence or if an error occurs during the input operation.

When cin.getline() reads from the input, there is a newline character left in the input stream, so it doesn't read your c-string. Use cin.ignore() beore calling getline().

cout<<"Journal Entry:\t";
cin.ignore();
cin.getline(journal,23);



回答2:


Adding to what @DavidHammen said:

The extraction operations leave the trailing '\n' character in the stream. On the other hand, istream::getline() discards it. So when you call getline after an extraction operator, '\n' is the first character it encounters and it stops reading right there.

Put this after before getline call extraction:

cin.ignore()

A more robust way of taking input would be something like this:

while (true) {

    cout<<"Time:\t";
    if (cin>>time) {
        cin.ignore();  // discard the trailing '\n'
        break;
    } else {
        // ignore everything or to the first '\n', whichever comes first
        cin.ignore(numeric_limits<streamsize>::max(), '\n');
        cin.clear();  // clear the error flags
        cout << "Invalid input, try again.\n";
    }
}



回答3:


You're not checking stream status. The std::cin stream extraction operator (operator>>) can fail. When it does, the stream is marked as "bad" (failbit, badbit, or eofbit are set). Once "bad", all subsequent stream extractions on that stream will fail unless you clear the status.

Learn to be a paranoid programmer. Always check status of those formatted input operations. You could, for example throw an exception, or print an error message and exit. The one thing you shouldn't do is to simply assume that it worked.



来源:https://stackoverflow.com/questions/12691316/getline-does-not-work-if-used-after-some-inputs

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!