Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

input stream with string

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

#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 ?

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading