I have an annoying problem with this piece of code:

int len = 5;
char str[5];

do {
    cout << "Enter a string: ";
    cin.getline(str, len);
} while (true);

when the length of str is less than 5, the code runs fine. I can re-enter the string over and over. But when I enter a string with the length greater than 5, the loop repeats forever without letting me to enter the string. So what is the problem here?

Recommended Answers

All 2 Replies

getline stops reading when one of three things happen.

  1. EOF is hit on the stream and the eofbit is set
  2. the delimiter for that function call is found. the default is '\n'
  3. the array is filled up to n-1 and the failbit is set

if the stream state isn't good, if cin.good() doesn't return true, any calls for input fail. That's what's happening with your code. after the first getline, the third stopping rule is hit and failbit is set. but because failbit is set, cin.good() doesn't return true and all of the next getlines are ignored.

you fix it by checking the state, fixing any problems, and clearing the state.

#include <iostream>
#include <limits>

using namespace std;

int main() {
  int len = 5;
  char str[5];

  do {
    cout << "Enter a string: ";
    cin.getline(str, len);
    if ( cin.eof() ) {
      break;
    } else if ( cin.fail() ) {
      // Clear the stream state back to good.
      cin.clear();

      // Clear the leftover line.
      cin.ignore( numeric_limits<streamsize>::max(), '\n' );
    }
  } while (true);

  return 0;
}

The clear method sets the stream state back to good, and you have to do that before you can do any reading or writing with the stream. The ignore method is like getline except that it doesn't save the characters anywhere. They just get thrown away. The whole numeric_limits thing just says that ignore should throw away up to as many characters a the stream can hold. The delimiter is '\n' so ignore will throw away as many characters as possible up to the next line break. :)

Well, I don't know that a simple input statement requires subtle manipulations. Thank a lot Hamrick, your answer is very informative and help me get a better understanding of C++ input operation.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.