I am trying the following code:

int main() 
{
    char str1[20];
    int a;
    cout << "Enter Integer:"
    cin >> a;
    cout << "Integer:"<<a<<endl;
    cout << "Enter string:"<<endl;
    cin.getline(str1,20);
    cout << "Input String is:"<<str1;
    return 0;
}

and OUTPUT is:

Enter Integer:20
Integer:20
Enter string:
Input String is:

I am able to enter the string when not accepting integer using cin, but when I try to use cin.getline() after cin, its not working.

Can anybody help?

有帮助吗?

解决方案

The problem is that operator>> ignores whitespace (i.e. ' ', '\t', '\n') before a field, i.e. it reads until before the next whitespace.

getline on the other hand reads until and including the next line break, and returns the text before the linebreak.

Consequently, if you do first operator>> before a line-break and then getline, the operator>> will read until before the line-break, and getline will read only until after the line-break, returning an empty string.

Note: what you have in the input buffer after entering "20, 20, mystring" is effectively

20\n20\nmystring

Hence

  • the first operator>> reads and returns 20
  • the second operator>> reads until after the second 20, swallows the first \n and returns the second 20
  • getline reads until the second \n and returns the text before that, i.e. nothing.

其他提示

Try out the function gets(), i prefer it for accepting strings and the only parameter that you need to pass is the string name.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top