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.
#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;
}
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;
}