简体   繁体   中英

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

I am trying to print inputs until user gives a blank input.So,I used getline(cin,input).But,When i use getline(cin,input).It is 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 the condition of nested loop

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

My suggestion is to simplify the program as follows:

#include <iostream>
#include <string>
using namespace std;
int main() {
    while(1)    // only one loop is 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 only nested loop without while(1) , eg:

#include <iostream>
#include <string>
using namespace std;
int main() {
    string n;

    while(getline(cin,n) && !n.empty())
    {
        cout<<n<<endl;
    }

    return 0;
}

The problem is

    getline(cin, n);                         // here
    while(getline(cin,n) && !n.empty())

That first getline reads input ( the first line ), but you discard and read again in your

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

So, remove that first getline , that should give you the desired outcome.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM