0

While running the loop why is it missing the first time when it runs, it does not take any input when runs first time

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

loop runs for T=1, but does not take any input but gives a new line.Why?

anastaciu
  • 20,013
  • 7
  • 23
  • 43
  • `std::cin >> T` doesn't "eat" trailing new line. (but leading spaces). – Jarod42 Mar 23 '20 at 18:58
  • 1
    You have a dangling newline left over after the integer input. Almost certainly discussed already on SO ... looking for it ... – Adrian Mole Mar 23 '20 at 18:58
  • The `>>` operator skips leading whitespace, and doesn't consume the delimiter after the input. `std::getline` doesn't skip leading whitespace, but will consume the delimiter. If you use `std::getline` after `>>`, `std::getline` will read the newline left by `>>` and stop immediately. – BessieTheCookie Mar 23 '20 at 19:08
  • A quick fix would be to use `cin.get();` after `cin >> T;`. – anastaciu Mar 23 '20 at 19:21

0 Answers0