在 while 循环中使用 std::cin 在添加多个数字时读取多个数字(循环不会终止)
Using std::cin in a while loop to read multiple numbers while they're being added (Loop won't terminate)
我正在做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;
}
相关文章:
- 使用fstream对txt文件中的数字进行循环
- 在 c++ 中查找字符串中没有循环的数字总和
- 程序以使用 C++ 中的 while 循环查找一组数字的最小值
- 遇到此问题时遇到困难:允许用户输入数组的值并使用 for,而循环也输出输入的最大数字
- C++ for 循环,用于反转数字 10 - 99
- 为什么当我输入一个被接受的数字时,我的 do-while 循环没有中断?
- 如何使用循环对所有数字求和?
- 循环中的线程 Runnin 用于对 c++ 中的数字求和
- 为什么我的 while 循环永远不会在 C++ 中的数字猜测游戏中结束?
- C++在不使用pow或循环的情况下计算一个数字的幂
- 我必须更改我的数字最后一个数字和第一个数字,但不要使用仅带有整数或循环的函数.例如从 12345 到 52341
- 如果输入数字为负数,如何循环
- 如何循环开关语句直到找到所需的数字?
- 如何在C++中创建 2d 数组,其中一部分包含循环计数器,另一部分包含数字列表?
- C++ 循环快乐数字 CS101.1X
- 在循环中使用字符串流从几个字符串中提取数字
- 如何制作 arduino 串行循环(连续接收数字)
- 有什么方法可以在 c++ 中组织"cycling"(循环)数字?
- 嵌套循环:数字模式
- 而循环-C++数字计数的怪异错误