在java中,您可以执行以下操作:
Scanner sc = new Scanner(System.in);
int total = 0;
for(int i = 0; i<something;i++){
total+=sc.nextInt(); // <<< Doesn't require an extra variable
}
我的问题是:你能用C或C ++做类似的事吗?如果有,是否更好?
这就是我目前所做的事情:
int total;
int aux; // <<< Need an extra variable to read input
for(int i = 0; i<something;i++){
scanf("%d",&aux);
total+=aux; // <<< and add the read value here
}
答案 0 :(得分:1)
在C ++中使用它的显而易见的方法是这样的:
int total = std::accumulate(std::istream_iterator<int>(std::cin),
std::istream_iterator<int>(),
0);
就目前而言,这可以从输入文件中读取所有int
,而不需要单独指定输入值的数量。你可以指定一个N
如果你想要足够严重,但至少根据我的经验,你不太可能想要那个。{/ p>
如果你真的想直接指定N,那么处理这种情况的最简洁方法可能是定义一个与accumulate_n
类似的std::accumulate
:
template <class InIt, class T>
T accumulate_n(InIt in, size_t n, T init) {
for (size_t i=0; i<n; i++)
init += *in++;
return init;
}
您可以像以前的版本一样使用它,但(显然已经足够)指定要读取的值的数量:
int total = accumulate_n(std::istream_iterator<int>(std::cin),
something,
0);
我想我应该添加它(特别是对于生产代码),你可能想在上面的accumulate_n
定义中为模板参数添加一些约束。我也没有尝试对输入错误的可能性做任何事情,例如包含除数字之外的其他内容,或者只包含少于指定的项目。这些可以处理,但我不记得Java是如何处理它们的;我可能不得不做一些思考/研究,以找出/弄清楚对这些问题的反应最合适。
答案 1 :(得分:0)
用c ++从输入流中读取一些变量通常如下(关于你的样本):
int total = 0;
int aux;
while(std::cin >> aux) {
// break on 'something' condition
total += aux;
}
所以,我没有看到如何在没有辅助变量的情况下执行它的方法,它实际上接收从std::istream
读取的值,除非你提供了一个包装类你自己,只是提供 java喜欢的行为。
&#34;你能用C或C ++做类似的事情吗?如果有,是否更好?&#34;
我怀疑在c ++中为std::istream
编写这样的包装类是值得的(您可以考虑使用std::accumulate()
中提到的@JerryCoffin's answer算法)。
对于c语言,没有其他选择,我实际上可以看到/了解。