在 c++ 中如何使循环成为输入以检查其是否有效

in c++ How to make a loop an input to check if its valid or not?

本文关键字:输入 检查 有效 是否 c++ 何使 循环      更新时间:2023-10-16

试图找出如何接受输入并检查它是否有效,如果有效,答案在 main 中转换为 int,然后传递到我的开关中。但是,我不断收到错误。我怎么能做到这一点,或者这只是在抵达时死了。还有没有更短的方法可以获得相同的结果?我是编程新手,任何帮助将不胜感激。这是类的主体。

#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;
}

我真的不明白你要什么,但我会给你一些帮助:

1)像if (Answer = 1)这样的代码是完全错误的(但它是可编译的),因为您肯定要Answer与数字1进行比较,而不是将1分配给Answer然后将其用作if语句的条件。若要比较两个值,请使用==例:

if (Answer == 1)

2)if (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 */
}