0

I want to detect enter pressed to break loop. If user press 2 enters in a row, loop breaks. I'm using vector to store user input. All variable's type is integer.

#include <iostream>
#include <vector>

using namespace std;

int main()
{   int buffer;
    vector<int> frag;
    do
    {
        cin >>buffer;
        frag.push_back(buffer);
    }while(frag.end()!='\n');


}

How can I escape from error message "no match for 'operator!=' (operand types are 'std::vector::iterator....."?

Yohan Kim
  • 19
  • 2

1 Answers1

0

You can compare std::cin.get against \n:

std::vector<int> vecInt;
char c;

while(std::cin.peek() != '\n'){
    std::cin.get(c);

    if(isdigit(c))
        vecInt.push_back(c - '0');
}

for (int i(0); i < vecInt.size(); i++)
    std::cout << vecInt[i] << ", ";

The input : 25uA1 45p
The output: 2, 5, 1, 4, 5,
  • If you want to read in two integer values so after hitting Enter key for the second time it will stop reading:

    std::vector<int> vecInt;
    int iVal, nEnterPress = 0;
    
    
    while(nEnterPress != 2){
    
        if(std::cin.peek() == '\n'){
            nEnterPress++;
            std::cin.ignore(1, '\n');
        }
        else{
            std::cin >> iVal;
            vecInt.push_back(iVal);
        }
    }
    
    for (int i(0); i < vecInt.size(); i++)
        std::cout << vecInt[i] << ", ";
    
    Input:  435  (+ Press enter )
            3976 (+ Press enter)
    
    Output: 435, 3976,
    
Raindrop7
  • 3,889
  • 3
  • 16
  • 27