String input using getline()

#include <bits/stdc++.h>
using namespace std;

int main()
{

int t;
cin>>t;
while(t--){
	string s;
	getline(cin,s);
	cout<<s;
}
return 0;

}
why the above code doesn’t print string s when input given is like this:
1
welcome home

I code in this way for first value string is not scanned or something else -

#include<bits/stdc++.h>
using namespace std;
int main(){
int t;
cin>>t;
for(int i=0;i<=t;i++)
{
    string s;
    getline(cin,s);
    if(i!=0)
        cout<<s<<endl;
}
return 0;
}

but why my code doesn’t give correct output can u please explain?

as i previously said the first string is not properly scanned if T is 5 then your programme will print only 4 strings :slight_smile:
@galencolin @ssjgz explain better why this is happen …

when you enter value of ‘t’ and press enter, line is changed which is nothing but “\n” and this line change or “\n” is registered as input by getline().
It can be avoided by adding cin.ignore() after test case input line.

int main()
{
        int t;
        cin>>t;
        cin.ignore();
        while(t--)
        {
                string s;
                getline(cin,s);
                cout<<s;
        }
        return 0;
}

I hope it helps.

2 Likes

thanks for clearing the doubt.