【发布时间】:2019-04-22 06:10:09
【问题描述】:
我需要按回车键来结束输入循环。试图找到一些东西,我这里有人说下面的代码可以工作,遗憾的是它没有。怎么了?
#include <iostream>
#include <sstream>
using namespace std;
int main() {
int a = 0, h = 0, i=0;
string line;
int *tab=new int;
while (getline(cin, line) && line.length() > 0) // line not empty
{
stringstream linestr(line);
while (linestr >> a)// recommend better checking here. Look up std::strtol
{
tab[i]=a;
}
i++;
}
return 0;
}
去吧,谢谢!
代码如下:
#include <iostream>
#include <sstream>
using namespace std;
int main() {
int a = 0, i=0;
string line;
getline(cin, line);
stringstream linestr(line);
int *tab = new int[line.size()/2+1];
while ( linestr >> a )
{
tab[i]=a;
i++;
}
for(int j=0; j<i; j++) cout<<tab[j]<<" ";
return 0;
}
【问题讨论】:
-
我很担心,为什么在这种情况下需要循环?如果你要按回车,那么你可以简单地使用一个输入流获取一个字符串并完成它。
-
int *tab=new int;然后tab[i]=a;.... 哦,孩子,你要过得很糟糕了 -
@Rivasa 我需要将整数输入到动态数组中,直到我按下回车键。我认为循环是方法。你的意思是我可以输入一个空格然后将其转换为整数?可悲的是我不明白;x
-
你不能那样做,你怎么知道一个数字什么时候结束?最好检查一个空输入。
-
@Rivasa 认为 line.length() == 0 会起作用。那我该怎么办呢?