C ++读取固定行数的整数行,每行中的整数数未知 [英] C++ Reading fixed number of lines of integers with unknown number of integers in each line
问题描述
我正在尝试读取数据并解决简单的问题,数据:
I'm trying to read in data and solve simple problem, data :
3 - number of lines to read in
1 1
2 2 2
3 4
每行输入后,我想获得输入数字的总和,但是每行中整数的数量是未知的.使用完以上数据后,屏幕应如下所示:
after each line is entered I would like to obtain sum of entered numers, but number of integers in each line is unknown. After using above data screen should look like this :
3
1 1
Sum: 2
2 2 2
Sum: 6
3 4
Sum: 7
但是从我的算法中,我得到了输出:
But from my algorithm I've got the output :
3
1 1
Sum: 1
2 2 2
Sum: 4
3 4
Sum: 3
我已经编写了代码,但是不能正常工作(如上所述): EDITION
我改进了代码,并知道它可以在不使用字符串等的情况下正常运行,下面是正确的代码:
I've written code, but it doesn't work properly (as above):
EDITION
I improved my code and know it works properly without strings etc., proper code is below :
#include<iostream>
using namespace std;
int main()
{
int x;
int t, sum;
cin >> t;
for(int i=0; i<t; i++) {
sum=0;
while(true)
{
cin >> x;
sum = sum + x;
if(cin.peek()=='\n')
break; //conditional break
}
cout << "Sum: " << sum << "\n";
}
return(0);
}
推荐答案
使用 getline
一次将一行读入 std :: string
类型的对象.然后使用该 std :: string
对象初始化一个 std :: istringstream
类型的对象,并使用提取器从流对象,直到失败.然后返回并阅读下一行.大概是:
Read a line at a time, using getline
, into an object of type std::string
. Then use that std::string
object to initialize an object of type std::istringstream
, and use an extractor to read int
values from the stream object until it fails. Then go back and read the next line. Roughly:
std::string line;
while (std::getline(std::cin, line)) {
std::istringstream in(line);
int sum = 0;
int value = 0;
while (in >> value)
sum += value;
std::cout << sum << '\n';
}
这篇关于C ++读取固定行数的整数行,每行中的整数数未知的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!