PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, October 30, 2022

[FIXED] How to take variable input from stdin in C++

 October 30, 2022     c++, eof, getline, stdin, string     No comments   

Issue

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.



Answered By - timrau
Answer Checked By - Robin (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing