c++ - Input using getline(cin,n); is not printing first input and i am not using cin>> to take input anywhere -


i trying print inputs until user gives blank input.so,i used getline(cin,input).but,when use getline(cin,input).it skipping first input while giving output.

#include <iostream> using namespace std; int main() {     while(1)     {         string n;         getline(cin, n);         while(getline(cin,n) && !n.empty())         {             cout<<n<<endl;;         }         if(n.empty())             break;     }     return 0; } 

sample input:

12   2 

output obtained:

2 

output needed:

12    2   

your code asks line twice :

1) before nested loop

  getline(cin, n); 

2) inside condition of nested loop

  while(getline(cin,n) && !n.empty()) 

my suggestion simplify program follows:

#include <iostream> #include <string> using namespace std; int main() {     while(1)    // 1 loop needed     {         string n;         getline(cin, n);   // read line         if(n.empty())      // check line             break;         // stop loop         else         {                cout << n << endl; // print line         }     }     return 0; } 

or leave nested loop without while(1), e.g.:

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

Comments

Popular posts from this blog

java - Spring Data JPA: Why findOne(id) executing delete query internally? -

python - Mongodb How to add addtional information when aggregating? -

java - Incorrect order of records in M-M relationship in hibernate -