英文:
getline doesn't allow me to enter multiple lines for input
问题
我正在编写一个程序,它的目的是从输入中获取一个整数 N,然后读取 N 行输入。然而,在运行时,它允许我输入 N,然后第一行,然后立即结束,而不等待后续行。例如,如果我输入:
3
Line 1
Line 2
Line 3
那么输出是 line entered no. 3: Line 1
,这是在我输入 Line 1
后立即发生的,这表明它正在完成循环。我该如何让它继续从我的控制台输入中读取更多行?查看其他问题和答案时,它们似乎都与混合使用 cin >> var
和 getline()
有关,但我在这里避免了这个问题,但仍然存在这个问题。
如果这是控制台的问题,我使用的是 Windows 10 上的 PowerShell。
#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;
}
英文:
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;
}
答案1
得分: 2
循环
for (i = 0; i < N; i++);
getline(cin, inptstr);
cout << "输入的行号:" << i << ":" << inptstr << endl;
是错误的。请注意,在`for (i = 0; i < N; i++);`后面立即有一个`;`。这意味着这段代码等同于以下内容:
for (i = 0; i < N; i++)
{
}
getline(cin, inptstr);
cout << "输入的行号:" << i << ":" << inptstr << endl;
换句话说,你的循环实际上什么也没做。
你可能想要的是以下内容:
for (i = 0; i < N; i++)
{
getline(cin, inptstr);
cout << "输入的行号:" << i << ":" << inptstr << endl;
}
英文:
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;
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论