Search code examples
c++stringstdingetlineeof

How to take variable input from stdin in C++


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.


Solution

  • You can write

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

    Only keep looping when the fetched string is nonempty.