c++ 如何修复此if-else语句,以便在输入错误字符串时循环?[已关闭]

balp4ylt  于 2022-12-15  发布在  其他
关注(0)|答案(1)|浏览(121)

已关闭。此问题需要details or clarity。当前不接受答案。
**想要改进此问题?**添加详细信息并通过editing this post阐明问题。

4天前关闭。
Improve this question
我对C++还是个新手,我们有一个任务,我需要写一段代码,我会问用户他们的课程是什么,正确答案应该只有三个:此外,如果用户输入了错误的课程,它将再次循环到问题“What 's your course?”,它应该一次又一次地循环,直到用户键入正确的课程。
所以我试着做我的代码,但它只是不断终止..请帮助我该怎么做。谢谢!

#include<iostream>
#include<string>
#include<sstream>
using namespace std;

int main (){
    string mystring;
    int BSIE, BSCPE, BSECE;
    cout << "\n What is your course? ";
    cin >> mystring;
    
    if(mystring == "BSIE"){
        cout << "     Your course is BSIE.";
    }else if(mystring == "BSCPE"){
        cout << "     Your course is BSCPE.";
    }else if(mystring == "BSECE"){
        cout << "     Your course is BSECE.";
    }else if(mystring != "BSIE"){
        cout << "\n What is your course? ";
        cin >> mystring;
    
    }
    
return 0;
}
6ie5vjzr

6ie5vjzr1#

您可以只使用do .. while循环

#include<iostream>
#include<string>
#include<sstream>
using namespace std;

int main (){
    string mystring;
    int BSIE, BSCPE, BSECE;
    
    do {
    cout << "\n What is your course? ";
    cin >> mystring; }
    while (mystring != "BSIE" && mystring != "BSCPE" && mystring != "BSECE");
    cout << "\n Your course is " << mystring;
    
return 0;
}

它首先在do部分下执行代码,然后检查条件是否为真。如果条件不为真,则在do中重复代码。
您也可以使用递归函数,如下所示:

#include<iostream>
#include<string>
#include<sstream>
using namespace std;

string GetCourse(string course) {
    if (course == "BSIE" || course == "BSCPE" || course  == "BSECE") {
        return course; }
    cout << "\n What is your course? ";
    cin >> course;
    return GetCourse(course);
}
int main (){
    string mystring;
    int BSIE, BSCPE, BSECE;
    
    mystring = GetCourse("");
    cout << "\n Your course is " << mystring;
    
return 0;
}

这个函数在每次条件为false时调用它自己。当它变为true时,递归中断并返回值。

相关问题