Guess it ! and Why?

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

int main() {
int n;
cin>>n;

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

}

What will be output of the above code if the
input :
1
Hello I am CodeChef.

Probably the empty string; same reasons as this: My code is working fine on my cpu compiler but on codechef it shows wrong answers - #22 by ssjgz

2 Likes

Here we are checking the loop condition by the ‘n’ variable which value is 1 after one iteration ‘n’ value become 0 which terminate the loop and we got only one time iteration.

Can you explain why we get empty string ?
even if we use the following code
#include <bits/stdc++.h>
using namespace std;
int main(){
string s;
getline(cin,s);
cout<<s;
return 0;
}
and we get the whole line as output.

it is because as soon as you press enter after entering number then enter character is stored as a buffer which is sent to getline then as getline gets \n it just stops reading the string
try using fflush(stdin);

1 Like

With this it won’t wait for your string input(input =1) after you enter your count input i.e value of n; the new line character which is used for n is now used by getline() and it will soon terminated!

So, what can we do: use std::cin.ignore() just after your cin, It will help you to accept the string input.

How it works: So, basically bydefault std::cin.ignore() has argument 1 and ‘\n’ means it will ignore one character from previous input thus here It will work for you too, Cheers!

Note: fflush() is better option when your code is in C-language but I think this is not efficient with C++ as some compiler may work with fflush() or some not.

1 Like

6

after cin >> n;
just add cin.ignore();
to ignore \n when the input is given because you are giving the input in two different lines and \n is consider as the input for the string