1

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
user3250183
  • 506
  • 6
  • 19

2 Answers2

2

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
}
Community
  • 1
  • 1
herohuyongtao
  • 49,413
  • 29
  • 133
  • 174
  • This scheme requires a sentinel value though, because `cin` will hang after the last value waiting for the user to type something. – Matthieu M. Feb 11 '14 at 16:30
  • @herohuyongtao: actually, the sentinel value could be anything else that is not a number (in which case your original solution worked), however it's unclear in the OP case whether there *is* anything at all sent after the list or we risk just hanging there. – Matthieu M. Feb 11 '14 at 16:35
  • @MatthieuM. Forgotten this. Updated. Many thanks. :) – herohuyongtao Feb 11 '14 at 16:38
  • Traditionally, one sends EOF (with e.g. ^D) to signify end-of-input. What's wrong with that here? Alternatively simply break on the 10th iteration. – Lightness Races in Orbit Feb 11 '14 at 16:44
  • @LightnessRacesinOrbit: `^D` certainly seems the way to go, it just must be considered. – Matthieu M. Feb 11 '14 at 16:48
  • @LightnessRacesinOrbit Yes, `^D` will end the input. However, OP's code will still print last value twice (one more time after `^D`). Is this because `cin>>` leaves a newline? – herohuyongtao Feb 11 '14 at 17:18
  • 1
    @herohuyongtao: No, it's because his loop is incorrect. He checks the stream state _before_ reading from it, not _after_. It's the daily `while (!eof)` bug again. Your fix is correct. – Lightness Races in Orbit Feb 11 '14 at 17:20
  • @LightnessRacesinOrbit You awaken me. Update the answer. Many thanks. – herohuyongtao Feb 11 '14 at 17:26
0

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

Nipun Talukdar
  • 4,975
  • 6
  • 30
  • 42