首页 > 解决方案 > 我想运行一个是/否循环来使用向量输入学生列表并显示它,直到用户选择输入学生姓名

问题描述

这是我的代码,我不明白我做错了什么。每次按下“y”或“Y”后,输入字符串不会连续工作。相反,它在第一次输入字符串后一次又一次地显示问题消息。

int main(){
    vector<string> v;
    int count=0;
    bool value=true;
    string s;
    char ch;
    cout<<"Start entering the name of the students :- "<<endl;
    while(value){
        getline(cin,s);
        v.push_back(s);
        count++;
        cout<<"Do you want to Enter one more name :- Press 'y/Y' to continue or 'n/N' to end -> ";
        cin>>ch;
        if(ch=='n'||ch=='N') value=false;
    }
    cout<<"So, there are total "<<count<<" number of students and their names are :-"<<endl;
    for(auto x:v) cout<<x<<endl;
    return 0;
}

标签: c++stringc++11vectorwhile-loop

解决方案


我认为,当我们输入数值时,我们按下回车键,因此回车键也进入输入,但 cin 在输入之前取值并将输入留在流中,所以当我们获得下一个输入时进入并且我们的输入被跳过(空)这导致了这个问题。

所以我们应该总是使用 cin.ignore(); 在每个整数输入之后。其他数字输入可能会发生同样的情况。在您的情况下,它发生在 char 输入上,这也是一个整数输入,因此它是预期的并且它可以工作,您可以检查我提供的解决方案。

int main(){
    vector<string> v;
    int count = 0;
    bool value = true;
    string s;
    char ch;
    
    cout<<"Start entering the name of the students :- "<<endl;
    while(value){
        getline(cin,s);
        v.push_back(s);
        count++;
        cout<<"Do you want to Enter one more name :- Press 'y/Y' to continue or 'n/N' to end -> ";
        cin>>ch;
        cin.ignore();
        if(ch == 'n'|| ch == 'N') {
            value = false;
        }
    }
    cout<<"So, there are total "<<count<<" number of students and their names are :-"<<endl;
    for(auto x:v) cout<<x<<endl;
    return 0;
}

推荐阅读