Home > Enterprise >  input stream with string
input stream with string

Time:01-12

If I type john when prompted for a char, the while statement will loop 4 times, one for each letter of john, before it asks again for user input.

Why does this program do not allow me insert more input before the whole 4 chars of john are consumed ? I would expect it to discard the 3 remaining letters of the string john and asked me for more input on the second loop.

The whole example can be found at page 44 of Bjarne Stroustrup The C Programming Language 4th edition.

#include <iostream>
using namespace std;

bool question() {
  while (true) {
    cout << "Continue ?\n";
    char answer = 0;
    cin >> answer;
    cout << "answer: " << answer << endl;
  }
  return false;
}

int main () {
  cout << question() << endl;
}

The output becomes:

Continue ?
john
answer: j
Continue ?
answer: o
Continue ?
answer: h
Continue ?
answer: n
Continue ?

CodePudding user response:

You may be wondering why you're not being allowed to enter a character at each prompt. You have entered four characters into the input stream, so your loop runs four times to consume all of that input.

If you only want to use the first character in the input, you may want to get an entire line and work on just the first character.

#include <iostream>
#include <string>

bool question() {
  while (true) {
    std::cout << "Continue ?\n";
    std::string line;
    std::getline(std::cin, line);
    std::cout << "answer: " << line[0] << endl;
  }
  return false;
}

Of course, you should also check that an empty line was not entered, which may be as simple as checking if line[0] is not '\0'.

  •  Tags:  
  • c
  • Related