0

The following code is intended to concatenate words entered by the user.

#include <iostream>
#include <string>


int main() {
    // insert code here...

    std::string s;
    std::string concString;
    while (std::cin >> s)
    {
        concString = concString + s;
    }
    std::cout << concString << std::endl;
    return 0;
}

I am stuck in this while loop during execution because of which I am not able to print the concatenated string. How do I exit this loop? What is an invalid input for std::cin?

Neil Kirk
  • 21,327
  • 9
  • 53
  • 91
  • Use 'break' in a conditional statement to get out of a while loop. The condition could be anything from the maximum number of words read or a specific word encountered. – shark1608 Apr 01 '15 at 01:04

1 Answers1

0

Typically, a loop like that is stopped by end of file, rather than invalid input.

In a *nix environment, you can usually send an end of file to the terminal with CTRL+d, and at a windows console, CTRL+z.

See https://stackoverflow.com/a/16136924/1084944

You could, however, implement your own additional way to signify end of input. For example, having your users enter a blank line when done, or the word quit or such. Once you've chosen one, you should communicate that to the user, and you will have to structure your loop to be able to detect these conditions and exit.

Community
  • 1
  • 1