Will do, but I first need to grab a compiler. Don't have one on this computer.
Printable View
Will do, but I first need to grab a compiler. Don't have one on this computer.
Check the return values - cin is put into a fail state after the first getline, so until you clear it all subsequent reads will fail. See what happens when you change the first getline to:Code:if (!cin.getline(ch, 10))
cin.clear();
Yes, it solves the problem. I never really knew what cin.clear() did before this.
Why is cin put in fail safe mode? I can't find any information on getline() that describes that behavior?Quote:
Originally Posted by Daved
MSDN:
http://msdn.microsoft.com/library/de...rFunctions.aspQuote:
The second function extracts up to _Count - 1 elements and stores them in the array beginning at _Str. It always stores char_type after any extracted elements it stores. In order of testing, extraction stops:
* At end of file.
* After the function extracts an element that compares equal to _Delim, in which case the element is neither put back nor appended to the controlled sequence.
* After the function extracts _Count - 1 elements.
If the function extracts no elements or _Count - 1 elements, it calls setstate(failbit). In any case, it returns *this.
Thanks.
After playing around a bit with those two successive calls to getline(), this is what I came up with to make the program work in a predictable way:
Code:#include <iostream>
using namespace std;
int main()
{
char ch[3];
char left[3];
cout<<"Enter characters."<<endl;
cin.getline(ch,3);
if(cin.fail()) //then there are more characters to read
cin.clear();
else //the buffer is empty
cout<<"Enter some more characters:\n";
cin.getline(left, 3);
cout<<ch<<endl;
cout<<left<<endl;
return 0;
}