在C++中如何使一个循环输入以检查其有效与否。
试图找出如何获取输入并检查其是否有效,如果有效,则在main中将答案转换为int,然后将其传递到我的开关中。 但是,我不断地得到一个错误。我怎么才能做到这一点,或者这只是死在抵达。还有没有一种更短的方法可以得到同样的结果?我是编程新手,如有任何帮助,将不胜感激。这是类的主体在C++中如何使一个循环输入以检查其有效与否。,c++,C++,试图找出如何获取输入并检查其是否有效,如果有效,则在main中将答案转换为int,然后将其传递到我的开关中。 但是,我不断地得到一个错误。我怎么才能做到这一点,或者这只是死在抵达。还有没有一种更短的方法可以得到同样的结果?我是编程新手,如有任何帮助,将不胜感激。这是类的主体 #include "stdafx.h" #include "Switchs.h" Switchs::Switchs() { } Switchs::~Switchs() { } std::string Swit
#include "stdafx.h"
#include "Switchs.h"
Switchs::Switchs()
{
}
Switchs::~Switchs()
{
}
std::string Switchs::GetCase_Choice() // for retrieving the valid result
{
return Right_Choice;
}
//is equal to one override Right_Choice with result. if false pass to next case
std::string Switchs::Case_1(std::string Answer)
{
if (Answer = 1)
{
Right_Choice =Answer;
}
else
{
Case_2 (Answer);
}
return 0;
}
std::string Switchs::Case_2 (std::string Answer)
{
if (Answer = 2)
{
Right_Choice = Answer;
}
else
{
Case_3 (Answer);
}
return Answer;
}
std::string Switchs::Case_3 ( std::string Answer)
{
if (Answer = 3)
{
Right_Choice = Answer;
}
else
{
Case_Error (Answer);
}
return 0;
}
//if answer is not equal to above cases prompt them to reenter an answer then //enter code here pass that answer into Case_1
std::string Switchs::Case_Error (std::string Answer)
{
if (false)
{
std::string Choice_Num;
std::cout << "Please enter a number.";
std::cin >> Choice_Num;
Case_1(Choice_Num);
}
return 0;
}
我真的不明白你想要什么,但我会给你一些帮助: 像if-Answer=1这样的代码是完全错误的,但它是可编译的,因为您肯定希望将Answer与数字1进行比较,而不是将1指定给Answer,然后将其用作if语句的条件。 要比较两个值,请使用== 例如: 2如果为false,将永远不会执行内部代码。 我不知道你想做什么,但肯定不要跳过这些说明 3为什么从返回类型为std::string的函数返回0?这是毫无意义的 我建议您阅读一些基本的编程书籍,尤其是在深入OOP之前 编辑:如果您只是想检查一个数字是否包含在1到1337之间的范围内,只需执行以下操作:
int n;
std::cin >> n;
if (n > 0 && n < 1338)
{
/* do whatever you want */
}
else
{
/* number is not in the range */
}
……哎哟*夺走我的眼睛*。。。当您等待帮助时,请从中选择一个。顺便说一句,你为什么不使用一个简单的if-else梯子?if-false哈??你已经打开了所有的编译器警告,是吗?我同意WhiZTim的观点,这似乎是相当复杂的代码来做一些琐碎的事情。最后一个函数switch::Case\u Error。。。没有什么有用的。它只返回0。这是一种困惑吗?我怎样才能做到这一点呢?或者这只是到达时的死亡。还有没有一种更短的方法可以得到同样的结果?ifstr==xxx{/*doXXX*/}else ifstr==yyyy{/*doyy*/}else{/*doError*/}是处理字符串的正确方法,因为这些字符串不能用作switch语句中的变量。我现在只研究了几口编程,所以还有很多东西需要学习。我尝试循环使用案例开关,但没有得到我想要的结果。OP的代码实际上有更多的错误。是的,我知道,我只是想指出一些可怕的错误。
int n;
std::cin >> n;
if (n > 0 && n < 1338)
{
/* do whatever you want */
}
else
{
/* number is not in the range */
}