1

I was trying to take input variable number of strings and numbers.Found this solution link:

I tried this for numbers:

#include<iostream> using namespace std; int main(){ int np; while (cin>>np){ cout << np<<endl; } return 0; } 

for strings:

#include<iostream> #include<string> using namespace std; int main(){ string line; while (getline(cin, line)){ cout << line <<endl; } return 0; } 

But,when I run the code,even if I just press enter it doesn't come out of the loop.The loop should terminate if just an enter key is pressed,but that does not happen.

Please provide suggestions how to achieve this functionality.

7
  • 6
    Enter key is still a valid string. Commented Aug 16, 2017 at 16:14
  • then how to stop taking input if there is no other left? Commented Aug 16, 2017 at 16:15
  • 1
    Depends on OS. If memory serves, in Windows it's Ctrl+Z, in Unix it's Ctrl+D. Commented Aug 16, 2017 at 16:17
  • @Abstraction Some are Ctrl C too. Commented Aug 16, 2017 at 16:18
  • If you're reading data from a online judge it should put an end of stream in there for you. Commented Aug 16, 2017 at 16:20

1 Answer 1

3

You can write

while (std::getline(std::cin, line) && !line.empty()) { // ... } 

Only keep looping when the fetched string is nonempty.

Sign up to request clarification or add additional context in comments.

1 Comment

The one downside of this is that the loop breaks on empty lines, which may be undesirable. E.g. if you are a reading from a file and there are extra newlines, the above loop breaks on the first empty newline that is retrieved. But if one wants to read until there is no more input, i.e. until EOF, one can replace !line.empty() with !std::cin.eof().

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.