0
When I enter two numbers the sum is displayed.. but when I input character as yes not y... Then it goes into an infinite loop... can anyone explain why? int a,b; char ch; do { cout<<"Enter two numbers: "; cin>>a>>b; cout<<"The sum is "<<a+b <<"\nDo you want to try again (y/n): "; cin>>ch; }while(ch=='Y'||ch=='y');
please explain in detail
4 Antworten
- 1
how many people can give negative feedbacks without knowing what we are talking about?
- 1
int main(){
int a, b;
char ch ='y';
do{
cout << "Enter a number: ";
cin >> a >> b;
cout << "the sum is: " << a + b << "/n/n";
cout << "Do you want to add two more numbers?";
cin >> ch;
if(ch != 'y') {
Break;
}
}while(ch == 'y' ll 'Y');
Return 0;
}
- 2
It seems that 'y'of yes is stored in ch, then it tries to read numbers in "es" and it cannot, than arrives to the condition and found 'y' stored in ch, and so on in a loop.
You can solve it initializing ch='n' inside the do..while loop.
But neither I can understand in detail why this behavior...
Could someone explain what a program does when, asking for a number, it receives a string?
- 3
U can use if statment