2

When I write a program, and use the -

cout << "A:"; 
cin >> string_var; 
cout << "B"; 
cin >> string_var2; 

If there is a space in between the two inputs on the keyboard (for ex. If the console displayed:

A:_ (waiting for input) and I typed a a, the first a would go to the string_var and the second would go to string_var2. How can I flush the input stream?

someguy
  • 443
  • 3
  • 8
  • 13
  • I have used the functions cin.ignore() and cin.clear to no avail, but I'm not sure if I used them the right way... – someguy Jun 14 '11 at 04:44
  • @someguy - I don't know the answer but there is a statement `cout << "B";` to be executed in between. – Mahesh Jun 14 '11 at 04:47
  • I know but the a still goes to the second string_var2 – someguy Jun 14 '11 at 04:48
  • You can use getline to read the whole line, or call ignore until the input is consumed (ignore without args consumes one char only). – Kevin Jun 14 '11 at 04:48
  • Ok but what is the syntax of cin.ignore(whatgoeshere?) – someguy Jun 14 '11 at 04:49
  • INT_MAX works. It's the number of chars to ignore stopping at end of line. – Kevin Jun 14 '11 at 04:51
  • Ok, but then will it ignore my input even if I type it in a new stream (I think I know what I'm talking about when I say new stream but not sure) – someguy Jun 14 '11 at 04:52
  • It will take the first part of each string you type up to the white space. Is this what you want? – Kevin Jun 14 '11 at 05:01

2 Answers2

3

Instead of cin >> string_var, use cin.getline(string_var, 256, '\n'). Your current method of reading input only reads up till the first space. Using the getline method will read up to the \n character which is when the user hits enter.

marchica
  • 2,326
  • 23
  • 21
  • 5
    I thought the `istream::getline()` method only worked with C-style strings (`char*`): http://www.cplusplus.com/reference/iostream/istream/getline/ You want the global `getline(std::istream&, std::string&)` in `` http://www.cplusplus.com/reference/string/getline/, which doesn't require a `streamsize` argument. – Chris Morgan Jun 14 '11 at 05:10
  • @Chris Either way should work. I just assumed string_var was a char*. – marchica Jun 14 '11 at 05:27
  • The `char*` method requires more checking on the programmer's part, ensuring that `string_var` is always large enough for the results of `getline()`. In your example, the program would have issues if the user typed 257 characters before hitting return. – Chris Morgan Jun 14 '11 at 05:31
2

You can use cin.get() like this:

cout << "A: "; 
cin >> string_var; 
// clear remaining stream input
while(cin.get() != '\n'); 

cout << "B: "; 
cin >> string_var2;
greatwolf
  • 20,287
  • 13
  • 71
  • 105