"Alexander Malkis" <al*****************@stone.cs.uni-sb.de> wrote in message
news:c4************@hades.rz.uni-saarland.de...
How to recover from failing cin.get(str,n,'\n')?
The user pressed "Enter" on cin.get(...).I would like to let him try
once more but the system doesn't stop on the next cin.get. Code:
cin.get(str,n,'\n');
cout<<"haha\n";
char c;
/*
Now get '\n'. Doesn't work if the first time nothing else was input.
Have this line or leave it -it doesn't change the outcome in this case.
*/
cin.get(c);
cin.get(str,n,'\n'); //here doesn't wait if the first time Enter was
pressed.
if std::istream::get(T*, std::streamsize, T) does
not extract any elements, it sets std::istream::failbit.
(This function does not extract the delimiter T).
No further i/o will be performed until the stream state
is reset.
#include <ios>
#include <iostream>
#include <limits>
int main()
{
char str[100] = {0};
std::streamsize n(sizeof str);
std::cin.get(str, n, '\n');
std::cout << "one\n";
std::cin.clear();
std::cin.ignore
(std::numeric_limits<std::streamsize>::max(), '\n');
std::cin.get(str, n, '\n');
std::cout << "two\n";
return 0;
}
Rather than a simple 'std::cin.get()' to remove the newline,
I've used 'std::istream::ignore' instead, which will remove
any pending characters, the number of which might have exceeded
the value of the type 'streamsize' argument.
You could avoid all these machinations by using the
'std::getline()' nonmember function declared by <string>,
which stores the input in a 'std::string' object, and
does extract (but does not store) the newline character.
#include <iostream>
#include <string>
int main()
{
std::string line;
std::getline(std::cin, line);
std::getline(std::cin, line);
return 0;
}
-Mike