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

main function

int main(){
    long long int T;
    string s;
    cin >> T;
    while(T--){
        getline(cin, s);
        cout << s << endl;
    }
}

while loop skipping input on first iteration only printing blank lines

I want pass string as input on every iteration but on first iteration while loop is skipping input line.

Alexandre B.
  • 4,770
  • 2
  • 11
  • 33
  • 1
    The problem is that when you use cin>>T, it leaves a newline and that is being read by getline(). For more details refer to [this](https://stackoverflow.com/a/10311448/13198029) – Het Pandya Jul 24 '20 at 07:05

2 Answers2

1

cin >> T reads to the end of the number and not to the end of the line.

So with the first getline(cin, s); you read the rest of the line after the number.

You can call cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); right after the cin >> T; to ignore everything that is left in that line.

t.niese
  • 32,069
  • 7
  • 56
  • 86
0

You need to use std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); because it ignores the rest of the line up until "\n" or EOF.

Now the std::numeric_limits<std::streamsize>::max() is basically telling cin that there is no limit to the number of characters to ignore.

Also, it might make more sense to use a for loop.

For example:

#include <iostream>
#include <string>

int main()
{
    long long int T;
    std::cin >> T;
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    for (int i = 0; i < T; i--)
    {
        std::string s;
        std::getline (std::cin, s);
        std::cout << s << std::endl;
    }


    return 0;
}

Also check out why you shouldn't use using namespace std;

Geno C
  • 1,305
  • 3
  • 6
  • 22