-1
#include<bits/stdc++.h>
using namespace std;
int main() {
  int test;
  cin>>test;
  for(int i=0;i<test;i++){
   string name;
 
   getline(cin,name);
   cout<<name<<"\n";
  }

}

input
2
Pratik Patil
Niranjan shirdhone

output:
Pratik Patil

why this code not scanning string for second test case?

1 Answers1

1

When using the std::cin >> test syntax, a newline is always appended at the end as soon as Enter key is pressed. The leading newline inhibits the expected functionality of your program, it follows that it must be skipped or ignored somehow.

That's why std::getline() ignores the input. You need to discard that newline character. A simple solution to that is to call std::cin.ignore() after the the first extraction:

cin >> test;
cin.ignore();
...
Rohan Bari
  • 7,482
  • 3
  • 14
  • 34