循环C++以检查错误的输入,并在用户输入正确的输入时再次启动程序

Loops in C++ to Check Wrong Input and to Start Program Again if user enters Correct Input

本文关键字:输入 程序 启动 用户 C++ 检查 错误 循环      更新时间:2023-10-16

我是c++的新手。我已经布置了作业,我必须计算成绩并询问用户的意见。如果他输入错误,我必须重新启动程序。如果用户输入正确的输入,我必须处理数据并再次询问他是否要检查另一个计算。到目前为止,我已经编写了这段代码。如果用户输入错误的输入,我不知道如何在程序中再次循环,如果成功,则再次启动程序。请给我指导。谢谢。

#include <cstdlib>
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{   
    //Declaring Variable
    char choice;
    char input;
    //Promptin User to Enter his/her Choice
    cout<<"Enter C or c for Computer Science: n" ;
    cout<<"Enter S or s for Software Engineering: n";
    cout<<"Enter T or T for Telecom Engineering: n";
    cout<<"Select any option from the above Menu: ";
    cin>>input; 

    if (input != 'c' || input != 'C'){
        cout<<"Invalid input! Enter the correct input option again";
    }else if (input != 's' || input != 'S' ){
        cout<<"Invalid input! Enter the correct input option again";
    }else if (input != 't' || input != 'T' ){
        cout<<"Invalid input! Enter the correct input option again";
    }else if (input == 'a' || input == 'A'){
    }


    system("pause");
    return 0;
}
您可以使用

简单的do while循环来完成:

bool valid_input = false;
do
{
    // Code to read and validate the input...
} while (valid_input == false);

如果输入有效,则将valid_input设置为 true,循环将结束。


在不相关的说明中,如果您不区分大写或小写,请使用例如 std::tolower所以你只需要比较一次字母。F.D. std::tolower(input) != 'c' .

这是只要

在 switch 语句中定义答案就会提示用户回答的代码。 ans 是一个变量,用于保存字符 1 或 0 对应于用户的输入(无论是否在开关情况下定义(。如果定义,则 ans 得到 1 其他明智,它得到值 0。当 ans 为 1 时,执行 While 循环重复(在 switch 语句中定义(。

    #include <iostream>
    #include <cstdlib> 
    using namespace std;

int main() {
 char input; 
 char ans; //correct answer, incorrect answer

 do {
    cout<<"Enter C or c for Computer Science: n" ;
    cout<<"Enter S or s for Software Engineering: n";
    cout<<"Enter T or T for Telecom Engineering: n";
    cout<<"Select any option from the above Menu: ";
    cin>>input; 
      switch (input){
        case 'S': 
          ans = 1; 
          break; 
        case 's': 
         ans = 1; 
         break;
        case 'C': 
          ans = 1; 
          break;
        case 'c': 
         ans = 1;
         break; 
        case 'T': 
          ans = 1; 
          break; 
        case 't': 
         ans = 1; 
         break;
       default:
      ans = 0; 
}
} while (ans);

 return 0;
 }

用户输入处理非常常见,通常可以使用类似的模式。

基本上,您重新请求输入。 您处理有效的选择并中断循环,当选择无效时显示错误,并让循环再次询问输入。

备注1:在这里不使用开关盒,我可以立即脱离循环。我立即中断以避免两次指定条件或使用标志,这也是我使用没有结束条件的循环的原因。

备注2:std::flush用于在提示行上输入。 它确保在等待输入之前显示提示。

char inp = 0;
while (true) {
    std::cout << "Give input (a, b): " << std::flush;
    std::cin >> inp;
    inp = std::tolower(inp);
    if (inp == 'a') {
        std::cout << 'an';
        break;
    }
    if (inp == 'b') {
        std::cout << 'bn';
        break;
    }
    std::cout << "invalid choice (" << inp << ")";
}

无效选择处理可以通过此函数更通用一些,但有效选项的处理仍必须在本地完成:

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
char askInputChoice(const std::string& prompt, const std::vector<char>& valid)
{
    char inp = 0;
    while (true) {
        std::cout << prompt << ": " << std::flush;
        std::cin >> inp;
        inp = std::tolower(inp);
        if (std::find(valid.begin(), valid.end(), inp) != valid.end()) {
            break;
        }
        std::cout << "invalid choice (" << inp << ")n";
    }
    return inp;
}
int main()
{
    char inp = askInputChoice("Give input (a, b)", std::vector<char>{'a','b'});
    switch (inp) {
    case 'a':
        std::cout << "an";
        break;
    case 'b':
        std::cout << "bn";
        break;
    }
}

要重新启动程序,请将其置于 while 循环中,添加一个退出选项('q'(,并在给出该选择时中断。

感谢大家的支持。实际上这是我在C++的第一个程序,对不起,我使用了指导这个词。实际上我已经成功编译了它。请检查我的程序,我知道你不需要,但我想知道我是否可以添加更多内容来改进它。

#include <cstdlib>
#include <iostream>
#include <conio.h>
using namespace std;
int main(int argc, char *argv[])
{   
    //Declaring Variable
    char choice;
    char input;
    int addTest = 0, matricMarks = 0 , interMarks = 0 , result = 0;
    start: //Label
    system("cls"); // Clear the Screen

    //Prompting User to Enter his/her Choice
    cout<<"Please Select the Degree Programme in which you are interested in to take Addmission: ";
    cout<<"nEnter C or c for Computer Science: "<<endl ;
    cout<<"Enter S or s for Software Engineering: "<<endl;
    cout<<"Enter T or t for Telecom Engineering: n"<<endl;
    cout<<"nSelect any option from the above Menu: ";
    cin>>input; 
    //Switch Statement Started
    switch(input){
        //Case C Started
        case 'c':
        case 'C':
                {
                    cout<<"Enter your Marks in Addmission Test: ";
                    cin>>addTest;
                    cout<<"Enter your Marks in Matric Degree: ";
                    cin>>matricMarks;
                    cout<<"Enter your Marks in Intermediate Degree: ";
                    cin>>interMarks;
                    result = (addTest * 0.20)+(matricMarks * 0.30)+(interMarks * 0.50);
                    if (result >= 70)
                    {
                        cout<<"nCongratulations! You are eligible for the Computer Science degree program :)"<<endl;
                    }  
                    else
                    {
                        cout<<"Sorry you Do not qualify for Computer Science Degree Programme: "<<endl;
                        system("pause");
                    }
                    break;
                }//Case C Closeed
    //Case s Started
        case 's':
        case 'S':
            {
                    cout<<"Enter your Marks in Addmission Test: ";
                    cin>>addTest;
                    cout<<"Enter your Marks in Matric Degree: ";
                    cin>>matricMarks;
                    cout<<"Enter your Marks in Intermediate Degree: ";
                    cin>>interMarks;
                    result = (addTest * 0.20)+(matricMarks * 0.30)+(interMarks * 0.50);
                    if (result >= 85)
                    {
                        cout<<"nCongratulations! You are eligible for the Software Enginnering degree program :)"<<endl;
                    }  
                    else
                    {
                        cout<<"nSorry! you Do not Qualify for Software Engineering Degree: "<<endl;
                        system("pause");
                    }
                    break;
            }//Case S Closed
    //Case t Started
        case 't':
        case 'T':
            {       
                    cout<<"Enter your Marks in Addmission Test: ";
                    cin>>addTest;
                    cout<<"Enter your Marks in Matric Degree: ";
                    cin>>matricMarks;
                    cout<<"Enter your Marks in Intermediate Degree: ";
                    cin>>interMarks;
                    result = (addTest * 0.20)+(matricMarks * 0.30)+(interMarks * 0.50);
                    if (result >= 80)
                    {
                        cout<<"nCongratulations! You are eligible for the Telecom Engineering degree program :)"<<endl;
                    }  
                    else
                    {
                        cout<<"Sorry you Do not Qualify for Telecom Enginnering Degree Programme: "<<endl;
                        system("pause");
                    }
                    break;
            }//Case t Closed
    //Default Case Started
        default:
            {
                   cout<<"nInvalid input! Enter the correct option again: n";
                    system("pause");   
                    goto start;                   //Jump To Label Start      
            }//Deafult Case Closed
    }// Switch Statement Close
    //do while Loop Started
    do{
        cout<<"nDo you want to check your eligibility in some other degree program y/n? : ";
        cin>>choice;
        if (choice=='Y'||choice=='y')
         {
          goto start;                                   //jump to Label start:
         }
        else if (choice=='N'||choice=='n')
         { 
           break;
         }
        }while(choice  == 'y' || choice == 'Y');
    //Do while Loop Closed


    system("pause");
    return 0;
}