while循环错误或如何解决? [英] while loop bug or how to fix it?

查看:120
本文介绍了while循环错误或如何解决?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好!
为什么当我输入一个整数时,它可以完美地工作(下面的代码),但是当我输入一个char类型的simbol时,它会变得疯狂并永远运行一行吗?我知道这是不同变量类型的问题,并且编译器无法简单地理解需要输入的内容.
如何定义变量,即如果您输入字符类型,则将其转换为数字并按条件进行常态循环,或者可能如何定义,您只能输入数字?

Hello everyone!
Why when i enter an integer it''s work perfect(code below), but when i enter a char type simbol it''s going crazy and loop run a single line forever? I understand that is a problem with the diferent variable types and compiler do not understand simply what need to enter.
How to define variable, that if you enter a char type, it converts to number and do normaly loop by condition or maybe how to define, that you could enter only a number?

do
{
int x;
std::cout << "Enter number: ";
std::cin >> x;

if (x == 1)
   std::cout "...";
   else if (x == 2)
   std::cout "...";
   else if (x == 3)
   std::cout "...";
   else
   std::cout "...";}
while (x < 1 || x > 3);
{
   x++;
}



有任何想法或提议吗? :)



Any ideas or offers? :)

推荐答案

循环问题太简单了.

问题是您使用的条件及其OR运算符(||),实际上,您定义了集{x < 1}和{x > 3}(即集outside)的 union 段[1, 3]的长度.如果初始值为3或更大,它将无限增长.

您是真的意思AND(&&)运算符吗?

—SA
The problem with loop is way too simple.

The problem is the condition and its OR operator (||) you use, Actually your define the union of sets {x < 1} and {x > 3}, which is the set outside of the segment [1, 3]. Should initial value be 3 or more, it will grow infinitely.

Did you really mean AND (&&) operator?

—SA


可能-使用stringstream

此处:使用cin来获取用户输入. [基本输入/输出 [
Possible - using stringstream

Here: Using cin to get user input.[^]
This shows the way to convert the char to integer (a valid value if pssible.)

More details here:Basic Input/Output[^]


UPDATE:
Just came across this too (a good alternative): use std::cin.good() - It is 0 if the input is invalid.


问题已解决.我使用了字符串流.
The problem has been solved. I used string stream.
...
...
do
{
int x;
string xstr;
std::cout << "Enter number: ";
std::getline(std::cin, xstr);
std::stringstream(xstr) >> x;
if (x == 1)
   std::cout "...";
   else if (x == 2)
   std::cout "...";
   else if (x == 3)
   std::cout "...";
   else
   std::cout "...";}
while (x < 1 || x > 3);
{
   x++;
}



现在,即使您输入字符类型,它也能很好地工作.并且需要不要忘记包括...:D



And it works now good even you enter a char type. And need don''t forget includes...:D


这篇关于while循环错误或如何解决?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆