I am currently learning c and I have come to a strange behavior at my code:
#include<iostream>
using namespace std;
int main(){
int input;
int counter = 0;
while (input != 0 && counter <= 100){
cout << "-----------\n";
cout << "0 = Get Out!\nEverything else will be displayed!\nPlease enter a number: ";
cin >> input;
cout << "The number: " << input << "\n";
counter ;
}
return 0;
}
This Program itself works fine, but when I am typing a number as input, which is at least the maximum of the integer datatype 1, then this loop will be endless (I programmed a stop after 100 loops) and I cannot really explain this to me. In other languages the program just crashes or gives out an error, because the allocated storage is just not high enough for the data typed in, what is logic and I understand that, but why do the loop gets endless here, that does not make any sense, because I cannot do any inputs after this happens, it just keeps doing the loop with the value (integer maxnumber, in my book stands, that the maxnumber can vary from system to system, so I do not type my number) endlessely and I cannot do anything, but watch my console getting flooded with the same 4 lines.
I would really appreciate, if somebody could explain this phenomena to me, I mean it is not crucial, but it catched my interest anyways.
CodePudding user response:
- Your
input
variable needs to be initialized because you check its value in thewhile (input != 0 && counter <= 100){
before assigning the input value. - Undefined Behaviour is typical in C when exceeding data type limits. These are some common UB.
- This post contains the "solution" to your problem
CodePudding user response:
How about the following? Is this what you want?
#include<iostream>
using namespace std;
int main(){
int input;
int counter = 0;
cout << "0 = Get Out!\nEverything else will be displayed!\nPlease enter a number: ";
cin >> input;
cout << "The number: " << input << "\n";
while (input != 0 && counter <= 100){
cout << "Please enter the next number: ";
cin >> input;
cout << "The number: " << input << "\n";
counter ;
}
}