【发布时间】:2014-12-25 16:54:35
【问题描述】:
在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
}
【问题讨论】:
-
在 c++ 中我们通常使用
std::istream& operator>>(std::istream& is, T& val)而不是scanf()。后者是c-style,如果你真的想拥有它,请适当地标记你的问题! -
您好,感谢您的评论。我并不是特别在寻找 C 或 C++ 中的解决方案,只是一个效果最好的解决方案,我已经编辑了这个问题。
-
一行:
total+=atoi(fgets(aux, 256, stdin));