0

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;
		}
	}
}
2
Contributors
4
Replies
5
Views
9 Years
Discussion Span
Last Post by Narue
0

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;
    }
  }
}
0

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

0

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.

0

>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. ;)

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.