Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

getline doesn't allow me to enter multiple lines for input

I am writing a program which is meant to take from the input, an integer N, then read in N number of lines.
However when run, it allows me to enter N, then the first line, and then immediately ends without waiting for the following lines. E.g., if I input

3
Line 1
Line 2
Line 3

Then the output is line entered no. 3: Line 1, which happens immediately after I enter Line 1, which suggests it is completing the loop.
How can I get it to read further lines from my console input? Looking at other questions and answers they all seem to stem from the use of cin >> var mixed with getline(), but I have avoided that here but still have the problem.

If it’s a matter of the console, I’m using Powershell on Win10.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

int main(void){
    int N, i;
    string inptstr, temp;

    getline(cin, temp);
    N = stoi(temp);

    for (i = 0; i < N; i++);
        getline(cin, inptstr);
        cout << "Line entered no. " << i << ": " << inptstr << endl;
    
    return 0;
}

>Solution :

The loop

for (i = 0; i < N; i++);
    getline(cin, inptstr);
    cout << "Line entered no. " << i << ": " << inptstr << endl;

is wrong. Note that you have a ; immediately after for (i = 0; i < N; i++);. This means that this code is equivalent to the following:

for (i = 0; i < N; i++)
{
}

getline(cin, inptstr);
cout << "Line entered no. " << i << ": " << inptstr << endl;

In other words, your loop effectively does nothing.

What you want is probably the following:

for (i = 0; i < N; i++)
{
    getline(cin, inptstr);
    cout << "Line entered no. " << i << ": " << inptstr << endl;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading