+ 1
Take numbers, but if encounter character, end
So this is the issue... Accept integers like 2 3 4... ( Undefined no. of integers) till end of file and give the sum of the numbers but if in the way, you encounter a character( eg 2 3 4 c 5....) , print ' invalid input' and terminate the program, do not give the sum
2 Réponses
0
only giving the function:-
void start(){
int i=0,sum=0;
cin>>x;
while(isdigit(x)){
sum+=x;
cin>>x;
}
if(!isdigit(x)){
cout<<"invalid input"
}
else cout<<sum;
}
0
@Tushar Purang - that prints invalid input every time ( I believe as the last read thing would be EOF even if there are all numeric inputs )
--------
Got the solution from a discussion at stack overflow
--------
Alright, so I found out that isdigit() is actually used to check if a character can be converted into a number or not ( I. E it lies within the range of '0' to '9' or not)
So this approach of yours will fail in the first try itself.
The solution is to take in all numbers as chars, read till end of file. However if any char appears( ie one which cannot be converted into an int ( not on the range '0'-'9')) , then isdigit () will return false (at which point one can return from the loop and end the program. Else one just prints the sum that is being calculated in every iteration