Weird c++ input escaping and space behavior
I'm having an unpleasant problem with my c++ example. Everything works fine until I enter something with a whitespace.
#include <iostream>
using namespace std;
int main (int argc, char * const argv[])
{
int iteration = 0;
while (true) {
char * input = new char[256];
scanf("%s", input);
cout << ++iterati开发者_如何学Goon << ": " << input << endl;
cin.get();
}
return 0;
}
So with this code, I can enter anything, but everything after whitespace is somehow like stored in buffer and used in the second iteration.
foo
1: foo
bar
2: bar
foobar
3: foobar
foo bar
4: foo
5: bar
Every single input reading function acts like this and it's driving me crazy. cin >> input
, freads()
, cin.get()
etc. all do this.
It this frequent problem with user input, or am I doing something wrong here?
First of all, never use scanf
. It's difficult to use that function and avoid buffer overflows. Replace input
with a std::string
, and read from std::cin
.
Both scanf("%s", input)
and cin >> input
will read one word, delimited by whitespace. If you want to read a whole line, then use getline(cin, input)
.
About scanf %s
format specifier:
This will read subsequent characters until a whitespace is found (whitespace characters are considered to be blank, newline and tab).
About istream::operator>>
with str parameter:
Extraction ends when the next character is either a valid whitespace or a null character, or if the End-Of-File is reached.
So yes, this is standard behaviour for these functions.
Maybe try using std::getline instead? http://www.cplusplus.com/reference/string/getline/
精彩评论