views:

52

answers:

3

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 << ++iteration << ": " << 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?

+1  A: 

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.

Péter Török
+4  A: 

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).

Mike Seymour
+1  A: 

Maybe try using std::getline instead? http://www.cplusplus.com/reference/string/getline/

Craig W. Wright