user2023328
user2023328

Reputation: 125

Learning C++ and I don't know what I did wrong here

I'm currently learning C++ and I was asked to write a code using the while function. The code runs, but it gives does not print the line Dear .... What did I do wrong here?

    cout << "Hello! Please write your recipient and the letter, then press enter:\n";
string name{ "" };
string current{ "" };
string letter{ "" };
cin >> name;
while (cin >> current){
    if (current != name){
        letter += " " + current;
    }
}
cout << "Dear " << name << "," << letter;
keep_window_open();
return 0;

Upvotes: 0

Views: 105

Answers (3)

clcto
clcto

Reputation: 9648

To output the result you have to make cin >> current false. To do this, use Ctrl-D to send end of file (EOF) to cin which will cause the loop to stop executing.

Edit: Apparently in Windows, the sequence is Ctrl-Z.

Edit: As @pdw noted, cout will need to be flushed. This is usually done when there is a newline character, but since you don't have one you can use std::flush or std::endl:

cout << "Dear " << name << "." << letter << std::flush;

Upvotes: 5

Joe Urc
Joe Urc

Reputation: 487

You have an infinite loop here. while (cin >> current) will always evaluate to true, and will just continuously wait for user input. That is why you never reach the last line of code. You are just continuously creating new values for current on each input in the prompt and then adding them to letter. I would recommend not using a while loop, or set some escape input. For example, if the user enters done, exit from the loop, using break;

Upvotes: 0

Slava
Slava

Reputation: 44238

while (cin >> current)

To make this loop interrupt you need to put end of stream marker into std::cin. Type Ctrl-Z on Windows or Ctrl-D on Unix like systems at the end of input to achieve that.

Upvotes: 0

Related Questions