0

Input numbers in a vector in C++ without any limit.When user press enter instead of a number it should print all the numbers inputted till now.

vector <int> numbers;
vector <int>::iterator i;
int num;
while(cin>>num && isdigit(num))
    numbers.push_back(num);

for(i=numbers.begin();i!=numbers.end();++i)
{
    cout<<*i<<'\n';
}

I am doing this thing but as soon as user press enter after taking suppose n numbers it exits the program w/o going to the printing loop.

3 Answers3

0

If you look at the function isdigit you see that it accepts a character.

Your input is an int.

isdigit checks to see if your num is in the range '0' (48) to '9' (57).

The isdigit call is entirely unnecessary.

Your program will work as it is if you input 49 50 51 52 [Return][Ctrl + D] or whatever you shell deems end of input. Or if you want cin>>num to fail, just input 51 52 53 acbd(not parseable as an int)[Return].

Captain Giraffe
  • 14,407
  • 6
  • 39
  • 67
0

Clearly, Your approach to read multiple numbers will need a different implementation.

Using cin >> num reads a single integer & press Enter to allow the buffer to be saved as int in num.So you will have to press Enter for every number.

But isdigit(num) fails and kills the while loop. Infact , isdigit is poorly used.

Why would you want to check int is a number or not.

isdigit takes a char type converts to int & find it falls in ASCII range of digits 48 to 57 ( 0,... 9 )

Proper use of isdigit is

char ch1 = '5';
char ch2 = 'a';
isdigit (ch1) // true
isdigit (ch2) // false

Remove isdigit () check on int which is pointless.

Now that the while loop depends only on cin>>num , you don't have any termination condition.

Possible approach would be to read multiple numbers could be read space delimited integers and convert into array , if the list of numbers are small enough.

Otherwise , read from File Stream or change the design of reading multiple numbers which relies on single enter to be pressed.

Sundar Rajan
  • 556
  • 4
  • 25
0

As mention by other isdigit will not serve your purpose. You need to check length of input line. If length is zero then user pressed entered, otherwise something which need to converter to integer.

Live Example

Manthan Tilva
  • 3,135
  • 2
  • 17
  • 41