-1

For the following code:

#include<bits/stdc++.h>
using namespace std;
int main()
{
    int t;
    cin >> t;
    while(t--)
    {
        string s;
        getline(cin,s);
        cout << s << "\n";
        cin.ignore(1000,'\n');
    }
    return 0;
}

Sample Input:

2

Name1

Name2

Expected output:

Name1

Name2

Error output:

Name2 // followed by blank line

I don't know why is it happening. I tried all the solutions given on stackoverflow but unfortunately none worked for me.Thanks in advance.

Community
  • 1
  • 1
Shivam Arora
  • 476
  • 5
  • 18
  • 1
    Remove the call to `ignore`. It's eating the next line. If you don't understand why, **read the specification** for `std::basic_istream::ignore`. – Pete Becker Jul 16 '17 at 20:19
  • Removing `ignore` also not producing the expected output. – Shivam Arora Jul 16 '17 at 20:24
  • Off topic: Careful with `#include` It's not saving you much work, it's non standard (so it only works on a single compiler) and combined with `using namespace std;` it's exposing you to some unnecessary risk. – user4581301 Jul 16 '17 at 20:26
  • The second problem is `cin >> t;` does not consume the new line that represents you pressing enter when typing in your input. This newline gets consumed by the first `getline` and results in an empty string. – user4581301 Jul 16 '17 at 20:30

1 Answers1

0

cin.ignore() is used to ignore the new line after inputting an integer. So,use cin.ignore() after cin>>t

#include<bits/stdc++.h>
using namespace std;
int main()
{
    int t;
    cin >> t;
    cin.ignore();
    while(t--)
    {
        string s;
        getline(cin,s);
        cout << s << "\n";
    }
    return 0;
}
Ghulam Moinul Quadir
  • 1,638
  • 1
  • 12
  • 17