我正在做C++初级读本中的练习1.16(第17页(。练习是从用户输入的(std::cin)
中获得一组数字,然后将它们相加并输出(std::cout)
。我的循环不会以std::cin >> input
为条件终止。一旦它用完了要添加的数字,它就会再次从键盘上读取。
我对C有点熟悉,在这种语言中,我相信我们可以做一些类似while (input != n)
的事情,但我不知道std::cin
的缓冲区末尾的字符是什么。std::cin
中的终止/最后一个值是什么?为什么它在我的条件下不起作用?
#include<iostream>
int main()
{
int x = 0;
int sum = 0;
std::cout << "Enter a set of integers: " << std::endl;
while (std::cin >> x)
sum += x;
std::cout << "The sum of those integers is " << sum << std::endl;
std::cin.get();
std::cin.get();
return 0;
}
我希望它在从输入缓冲区读取换行符时终止
在这种情况下,我会使用std::getline
将该行读取为std::string
,然后使用其中一个转换函数将该字符串转换为整数,如std::stoi
:
#include <string>
// ...
// exit the for loop if an empty line is entered
for(std::string line; std::getline(std::cin, line) && not line.empty();) {
try {
x = std::stoi(line);
sum += x;
}
catch(const std::exception& ex) {
// stoi can throw std::invalid_argument and std::out_of_range
std::cerr << line << ": " << ex.what() << 'n';
}
}
如果你想在每行上输入多个数字,你可以把你用std::getline
读到的行放在std::istringstream
中,然后从中提取数字:
#include <sstream>
#include <string>
// ...
for(std::string line; std::getline(std::cin, line) && not line.empty();) {
std::istringstream is(line);
while(is >> x) {
sum += x;
}
}
如果你仍然想做和用户输入一样多的数字,你可以用字符串输入,并检查输入是否是这样的数字(可能需要一些调整(:
int main()
{
int x = 0;
int sum = 0;
std::string input;
std::cout << "Enter a set of integers: " << std::endl;
while (std::cin >> input){
if( isdigit(input) ){ //may need to be "if( std::isdigit(input) ){"
x = std::stoi(input);
sum += x;
}
else{
break;
}
}
std::cout << "The sum of those integers is " << sum << std::endl;
std::cin.get();
std::cin.get();
return 0;
}