0

Here's My code and I can't get what am I doing wrong in this. It's not working continuously for input string after every pressed 'y' or 'Y'. Instead, it is displaying the Question message again and again after first string input.

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;
}
cam
  • 4,409
  • 2
  • 24
  • 34
  • 1
    Does this answer your question? [Why does std::getline() skip input after a formatted extraction?](https://stackoverflow.com/questions/21567291/why-does-stdgetline-skip-input-after-a-formatted-extraction) – Ted Lyngmo Aug 07 '21 at 08:18

1 Answers1

0

I think, when we get input of numeric values we press enter so the enter key also goes in input but cin takes value before enter and leaves enter in stream so when we get next input that enters comes in and our input get skiped(Empty) this is causing the issue.

so we should always use cin.ignore(); after every integer input. Maybe same case happen with other numeric inputs. In your case it is happening on char input which is also a interger input so it is expected and it work you can check my provided solution.

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