从cin中获取int的所有输入,用c++中的空格分隔



N=输入尝试次数(第一行(
s=输入可以添加的值(第二行、第四行和第六行(
P=输入用空格分隔的数字。

Example : 
3 ( Input N )
2 ( s 1 )
2 3
3 ( s 2 )
1 2 3
1 ( s 3 )
12
Example : 
Read #1: 5 (Output s1 = 2 + 3)
Read #2: 6 (Output s2 = 1+2+3)
Read #3: 12 (Output s3 = 12)

我已经搜索和尝试了很长时间,但无法弄清楚如何基于给定的数字,使用空格,并将所有值添加到变量中。例如:

#include <iostream>
using namespace std;
int main() {
int l, o[l], r, p[r], i;
cin >> l;
for(i = 0; i < l; i++) {
cin>>o[l];
r = o[l]; // for every o[0] to o[l]
}
while (cin>>o[l]) { 
for (i = 0; i < l; i++){
cin>>p[o]; // for every o[0] to o[l] 
// i.e o[l] = 1 then 2 values can be added (because it starts from zero)
// input 1 2 
// o[1] = {1, 2}
int example += o[1];
cout<< "Read#2: " << example;
}
}
}

但它不起作用。然后我找到了getline((,忽略了s,只输入任何最终会添加到数字中的内容,结果发现它只适用于char字符串。我试过扫描,但不确定它是如何工作的。所以我想知道这是否都是关于循环中的s(值(×1(列(矩阵,但我不知道如何制作它。有什么简单的解决方案吗?提前谢谢。

#include <iostream>
using namespace std;
int main() {
int t; //number of attempts
cin >> t;
while(t--) { // for t attempts
int n, s = 0; //number of values and initial sum
cin >> n;
while (n--) { //for n values
int k; //value to be added
cin >> k;
s += k; //add k to sum
}
cout << s << "n"; //print the sum and a newline
}
return 0;
}

如果您想添加更多详细信息(即第n次尝试打印Read#n(,您可以始终使用

for (int i = 1; i <= n; i++)

替换while(t-(,并在尝试结束时只打印

cout << "Read#" << i << ": " << s << "n";

相关内容

最新更新