DarkT
DarkT

Reputation: 179

How to keep looping until non-integer is entered

I have this program where I am trying to keep looping until something that is entered is a non-integer. No matter if I enter a non-integer or an integer the program still breaks and end. Please help

int data;
do
{
    cout<<"enter data: ";
    cin>>data;
    cout<<"yes"<<endl;
    return data;
} while(cin.good());

Upvotes: 0

Views: 1223

Answers (3)

rovy
rovy

Reputation: 2647

As you are defining data as integer you just have to check is cin When cin gets input it can't use, it sets failbit:

int data 
while(true)
{
    cout<<"enter data: ";
    cin>>data;   
    if(!cin) // or if(cin.fail())
    {
        // user didn't input a number
        break;
    }
     cout<<"yes"<<endl;
 }

Upvotes: 0

Alejandro
Alejandro

Reputation: 3082

This simple code snippet should work just fine.

#include <iostream>

int main() 
{
    int data;
    while(std::cin >> data)
    {
        std::cout << data << std::endl;
    }
}

Upvotes: 0

Roy Shmuli
Roy Shmuli

Reputation: 5019

Remove the return (or write it after the while) it break your code before the while line...

Upvotes: 1

Related Questions