Goal
New to c++ and haven't found a definitive answer on this question anywhere else. I'm working on a simple program that reads in a message typed in from the user on from within the console. It's an exercise for using string variables/concatenation.
I need to create loop that reads in the user input, which may contain multiple lines of input from the command shell.
So my function needs to read that input, while ignoring newlines, and end if a user inputs two "&&" on a new line.
Attempt
So here's my function:
string get_message() {
string message, line;
cout << "Enter the message > ";
cin.ignore(256, '\n');
while (getline(cin, line) && line != "&&") {
message = message + " " + line;
cout << message;
cin.clear();
}
return message;
}
The issue I'm running into is that within the while loop, until && is found, the loop content doesn't appear to run. Meaning when I cout << message I only get the single previous line of input.
Sample Run
Enter the Message > Messages.. this is a new message.
I'm a message on a new line, look at me.
New line.
&&
"New line." <--- from console cout
Result: New line.
Questions:
- When does the loop content get called?
- Why do I only get the previous line and not ALL previously (supposedly) concatenated lines?
- Is there a better way to code this?
message?cin.ignore(256, '\n');is eating your first input line, right?cin.ignore(256, '\n');? Mind you I can't work out why two lines appear to be ignored.cin.ignore(numeric_limits<streamsize>::max(), '\n');