user3250183
user3250183

Reputation: 516

Taking inputs if number of inputs is not known

I wish to take inputs from console where the number of inputs are not known. All i know is that they are less then or equal to 10.

I wrote this code but it evaluates the last value twice.

int x;
    do{
        cin>>x;
        cout<<check(x)<<"\n";
    }while(std::cin);

The inputs are in this form:

12 
2 
45

Upvotes: 1

Views: 413

Answers (2)

herohuyongtao
herohuyongtao

Reputation: 50667

As @LightnessRacesinOrbit commented, it's while(!eof) bug again. You should check the stream state after reading from it, not before.

You can use cin>>x in the while-condition and apply a special value (i.e. anything not a number) as the end flag like this:

while (cin >> x)
{
    // got a value
}

Upvotes: 2

Nipun Talukdar
Nipun Talukdar

Reputation: 5387

You may use istream::geline.

char input[1024]
std::cin.getline (input,1024);

After you read the line, you have to split it by white-spaces as delimiter. Just ignore 11th split onwards. And you may apply atoi or similar functions on the splits (some_split.c_str()) to get the numeric values

Upvotes: 0

Related Questions