program skipping cin statements

This program keeps skipping over the cin>>m>>n statement. I can't figure out why. I've tried adding commands like cin.ignore() of cin.clear() before that cin statement, but nothing seems to work. If I put something like "cout<<"hi";" at the end of the program, that line of code will still print. Any help is appreciated. Thanks!

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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
 

#include <iostream>
#include <vector>
#include <cmath>
#include <random>
#include <ctime>
#include <cstdlib>
#include <string>
#include <algorithm>

using namespace std;

vector<int>swap(vector<int>list, int m, int n);

int main(){
    int n,m,input;
    vector<int>list;
    vector<int>swaplist;
    
    cout<<"Enter an integer list, ending with a non-integer: ";
    
    while(cin>>input){
        list.push_back(input);
    }
    
    
    for(int i=0;i<list.size();i++)
        cout<<list[i]<<" ";
   
    cout<<endl;
    
    cout<<"Which entries would you like to switch? Separate by space: ";

    cin>>m>>n;
   
  
    swaplist=swap(list,n,m);
    
    for(int i=0;i<swaplist.size();i++)
        cout<<swaplist[i]<<" ";
    
   
}

vector<int>swap(vector<int>list, int m, int n){
    vector<int>replace;
    replace=list;
    
    replace[m]=list[n];
    replace[n]=list[m];
    
    return replace;
    
}
On line 23:
23
24
25
    while(cin>>input){
        list.push_back(input);
    }

After control leaves the body of the loop, std::cin is in a failed state. Reset it by dumping out everything still in the stream until a newline, and clearing the error state.
26
27
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
Last edited on
Thanks for the reply. I added both of those lines after that while loop, but when I run the program I get the same problem. Could something else be causing it?
Ah, sorry. You want space-separated inputs.
Replace
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
With
1
2
std::cin.clear()
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), ' ');

Last edited on
Topic archived. No new replies allowed.