如何在循环延续条件下区分数字 10 和 'n'?
How to Differentiate Number 10 from ' ' in a Loop-Continuation Condition?
我有以下代码部分:
cout << "Enter a series of integers: ";
cin >> integer;
while (integer != 'n')
{
cout << ...
cin >> integer;
} // end while
如果用户输入10,我的循环将中断,因为数字10=十进制的'\n'值。
我该如何解决这个问题?
谢谢,
您尝试的代码不起作用,因为操作cin >> integer
提取数字并将其转换为int。它无法区分行尾的位置。
相反,您应该读取一整行,然后从该行中提取整数,例如:
std::string s;
std::getline(std::cin, s);
std::istringstream iss(s);
int integer;
while ( iss >> integer )
{
// do something with integer
}
考虑先将用户的输入读取到std::string
中
如果不是换行符,请转换为int
并完成您的工作。
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
int main(){
std::string integer;
cout << "Enter a series of integers: ";
cin >> integer;
while (integer != "x") //<- can't be whitespace
{
cout << atoi(integer.c_str()) << std::endl;
cin >> integer;
}
}
默认情况下,输入流将跳过任何空白,包括换行符。换句话说,除非有人输入"10",否则输入值中永远不会有10。处理输入的一般方法是读取,直到读取失败(例如,由于EOF):
while(cin >> value)
{
// use value here
}
// failure, EOF or garbage on input
请注意,在之后读取任何其他内容之前,您必须先对流进行cin.clear()处理,并且其中仍然有垃圾,您必须对其进行cin.ignore(..)处理。也许您想使用getline()来使用基于行的输入,然后只需检查结果字符串是否为空,或者(尝试)将其解析为整数,否则。
#include <iostream>
int main(void)
{
int integer = 0;
std::cout << "Enter a series of integers: ";
std::cin >> integer;
while (integer != 'n' || integer == 10) {// **this will not work, it's wrong!**
std::cout << integer << std::endl;
std::cin >> integer;
}//end while
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 串行循环(连续接收数字)
- 使用 while () 循环从总和中减去数字
- 有什么方法可以在 c++ 中组织"cycling"(循环)数字?
- 我的堆栈使用链表时出错.无法打印数字循环.(C++)