0

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

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

4 Comments

FWIW since C++11 line[0] will always work. If the string is empty then you will get a null terminator.
@NathanOliver: IIRC it worked prior to C++11 as well.... The address of the terminator didn't have to be contiguous with the rest of the string unless c_str() had been called, but just reading it using operator[] was perfectly fine.
@BenVoigt In C++08/03 it was legal for a const std::string but UB otherwise. source: 21.3.4 basic_string element access
@NathanOliver: Ahh yes, can't have programmers overwriting the shared terminator storage. Still, that doesn't require const std::string, it just requires a const std::string&

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.