< Back to forum

Skipping Lines

#include <iostream>
#include<string>
using namespace std;

int main()
{
    int T, i;
    string A, B;
    cin >> T;
    for(i=0; i<T; i++)
    {
        getline(cin, A);
        getline(cin, B);
        
        cout << A << endl;
        cout << B << endl;
    }
    
    system("pause");
    return 0;
}

 

When working with strings, why does it skip line for string B for the first repetition. For instance,

Input

3

apple

 

banana

orange

Jackfruit

Grapes

Output

apple

 

banana

orange

Jackfruit

 

Even before I can type for the input of string B, it skips line and prints the output for string A. How can I prevent this?

Asked by: Abhinav_Lugun on April 7, 2019, 6:34 p.m. Last updated on April 7, 2019, 6:34 p.m.


Enter your answer details below:


Enter your comment details below:




3 Answer(s)

avatar

use console input instead of getline.

LIKE :)   cin >> A >> B;

rishup132 last updated on April 7, 2019, 6:34 p.m. 0    Reply    Upvote   

avatar

It is actually skipping for string A, not B. This is because getline() takes input unless it encounters a newline character ("\n" or when we press enter). So when it completes scanning the value for T, it goes to the new line to scan the value of A, but on getting that new line the first getline gets skipped and the value of A gets assigned to B.

To make it work, just add a cin>>ch after cin>>T (outside loop) where ch is of type character. It accepts the newline character after T. Now, it works!

Saptarshi_Dey last updated on April 7, 2019, 6:34 p.m. 0    Reply    Upvote   

avatar

if you want to use getline after using cin, add one line of code cin.ignore() after cin.

for example:

 cin >> T;
cin.ignore();
    for(i=0; i<T; i++)
    {
        getline(cin, A);
        getline(cin, B);
        
        
    }

 

Raghav_Grover last updated on April 7, 2019, 6:34 p.m. 0    Reply    Upvote   

Instruction to write good question
  1. 1. Write a title that summarizes the specific problem
  2. 2. Pretend you're talking to a busy colleague
  3. 3. Spelling, grammar and punctuation are important!

Bad: C# Math Confusion
Good: Why does using float instead of int give me different results when all of my inputs are integers?
Bad: [php] session doubt
Good: How can I redirect users to different pages based on session data in PHP?
Bad: android if else problems
Good: Why does str == "value" evaluate to false when str is set to "value"?

Refer to Stack Overflow guide on asking a good question.