a problem with vectors and cin

I've run into a problem using vectors and pushing numbers onto the vector. Here is some sample code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
 int main(){
    
    vector<double> list;
    double input;
    string response;
    
    do{
    cout<<"Numbers:";
    list.resize(0);
    
    while(cin>>input){
        list.push_back(input);
    }
    
    cout<<"The mean is "<<avg(list)<<endl;
    cout<<"The standard deviation is "<<std_dev(list)<<endl;
        
    cout<<"Again? (y/n)";
        cin>>response;
    
    }while(response=="y");
    
    return 0;
}


When I run this program, it terminates after printing "Again? (y/n)". This happens to me every time I try to read in numbers, put them into a vector using push_back, and then try to get something from the user later. Like if I took out that cin>>response line and had the program go on to do other things that don't involve getting input from the user, then the program would keep running. So I guess there is something wrong with my while loop. Any help would be appreciated.
Question is how do you escape the loop on line 11-13? I guess you input something that is not a number. When it fails to read a double it will set the failbit of cin. To be able to read input again you need to clear the failbit.
cin.clear();

The input that you entered to make the loop stop is still in cin so if you try to read a string now the string will get this value. To remove the old input before you read the string you can use the ignore function.
1
2
// Ignores one character.
cin.ignore();
1
2
 // Ignores the whole line.
cin.ignore(numeric_limits<streamsize>::max(), '\n');
Last edited on
I can't run your code, since you didn't post the entire program.

I don't think you need a while in line 11 & 13, unless your trying to get more than one value there. you have no comments so I can only guess at your intention.

For example, below you can get a single value. Add your code without the while loop in the middle and I think you may have it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
int main()
 {
	double input;
    string response;
    do{
    cout << "A Num: ";
	cin >> input;

    cout << "Input is : " << input << endl;
    cout << "Again? (y/n)";
    cin >> response;
    }while(response=="y");
    
return 0;
}


Other than line 11, the other problem I see is if your user types something besides a number, cin may throw you into a endless loop.

Thanks Peter87. Your cin.clear() command worked for me.
Topic archived. No new replies allowed.