Here's a fairly simple piece of code to get a message from the user, limiting its length to 10 chars. Problems arise when the message is 10 chars or more, and the program enters an infinite loop.

I think the problem is getline() leaving somethin on the stream, but I've tried using cin.ignore() to clear it, but it just doesn't happen.

Any help would be greatly appreciated.

#include <iostream>

using namespace std;

void main(){

	bool exitProgram = false;
	char selection, message[20];


	while(!exitProgram){
		cout << "Press 1 to continue or 2 to quit: ";
		cin.get(selection);
		cin.sync();
		cout << endl;
		
		while(selection != '1' && selection != '2'){
			cout << "choose 1 or 2: ";
			cin.get(selection);
			cin.sync();
			cout << endl;
		}

		if(selection == '1'){
			cout << "type a message. Messages will be shortened to 9 chars\n> ";
			cin.getline(message, 10);
			cout << "Your message: " << message << endl;
		}
		else{
			cout << "terminating\n" << endl;
			exitProgram = true;
		}
	}
}

Recommended Answers

All 4 Replies

First, be sure to read this thread. Second, getline is technically failing, which puts the stream into an error state and stops any further input from ever succeeding. You need to clear the state first:

#include <iostream>

using namespace std;

void main(){

  bool exitProgram = false;
  char selection, message[20];


  while(!exitProgram){
    cout << "Press 1 to continue or 2 to quit: ";
    cin.get(selection);
    cin.sync();
    cout << endl;

    while(selection != '1' && selection != '2'){
      cout << "choose 1 or 2: ";
      cin.get(selection);
      cin.sync();
      cout << endl;
    }

    if(selection == '1'){
      cout << "type a message. Messages will be shortened to 9 chars\n> ";
      cin.getline(message, 10);
      cin.clear();
      cin.sync();
      cout << "Your message: " << message << endl;
    }
    else{
      cout << "terminating\n" << endl;
      exitProgram = true;
    }
  }
}

Thanks for the advice, I'll have a read at that just now :-)

I have to say that thread is much more complete than the other information I'd found on google. I think even looked at that thread initially, but didn't read it fully because it appeared to cover everything I had already read.

I had tried cin.sync() but didn't ise cin.clear() first.

Good work, thanks.

>I have to say that thread is much more complete than the other information I'd found on google.
That's why I wrote it. I couldn't find the details that I thought were important on Google either, so I did it myself. ;)

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.