0

I have to read the test cast as follows.

3
ababa
abc
babac

c++ code to read the above input.

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

    while(t--){
        string s;
        getline(cin,s);
        cin.clear();
        cout<<s<<endl;
    }
    
    return 0;
}

but the output I'm getting is

ababa
abc

can you help me how to read the last line?

anfjnlnl
  • 63
  • 7

3 Answers3

2

When you do

cin >> t;

the Enter key you used to end that input is left in the input buffer as a newline. This newline will be read by the first call to getline as an "empty" line.

A simple solution is to ignore the remaining of the input after getting the input for t:

cin >> t;
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

I also recommend that you use the status of the stream as part of the loop condition:

string s;
while (t-- && getline(cin, s))
{
    cout << s << '\n';
}

This way you won't be attempting to read beyond the end of the input.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
0

Why not simply use cin >> s; unless there are multiple words in a string

#include <iostream>
using namespace std;

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

    while (t--) {
        string s;
        cin >> s;
        cout << s << endl;
    }
    
    return 0;
}
Shreevardhan
  • 12,233
  • 3
  • 36
  • 50
-1

To read the last line, you can use cin>>s; to read the string instead of

getline(cin,s);
cin.clear();```
samit
  • 78
  • 4
  • 8