I want to be able to enter integer numbers and if i enter a string of text or a character then i want the program to stop. and it seems to work but it just doesnt let me input anything else after a few numbers what am i doing wrong?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#include <iostream>
#include <string>
usingnamespace std;
int main()
{
int enter;
cout << "enter something" << endl;
do
{
cin >> enter;
}
while(enter != cin.bad());
}
Ok, i tried it and it works and also failbit seems to work better but when i enter a number i have to do it slow or i get the error message in the if statement, but if i typoe it in and wait a few secongds its fine, why is that?
You're testing the variable for invalid state with enter != cin.bad(), rather than testing cin itself for invalid state. This doesn't work because invalid input does not change a variable.
DO NOT use kaseron's suggestion--there's a new without an appropriate delete, which will cause a memory leak. Also, testing a pointer's value for != cin.failbit is just as incorrect as testing with enter != cin.bad().
Try this:
1 2 3 4 5 6 7 8 9 10 11 12
#include <iostream>
usingnamespace std;
int main()
{
int enter;
while(cin >> enter) //continues as long as valid integers are entered
{
//the rest of your code here
}
}
...or this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#include <iostream>
usingnamespace std;
int main()
{
int enter;
cout << "Enter an integer: ";
cin >> enter;
while(cin) //works just like while(cin.good())
{
//the rest of your code here
cout << "Enter another integer: ";
cin >> enter;
}
}
Ok i got it working, now i have a question about data type sizes, so an int is 4 bytes, so that means i can have 4 numbers in it? when i enter 10 numbers my program stops working so that tells me ive reached int's bit size and it stops working is that correct?
My program so far
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#include <iostream>
#include <string>
usingnamespace std;
int main()
{
int enter;
bool end = false;
cout << "enter something" << endl;
while(end != true)
{
cin >> enter;
}
}
The program seems to quit when i enter a larg amount of numbers then press enter.
The largest number a 4-byte integer can hold is 2147483647, while the smallest number it can hold is -2147483648. If you enter a number outside of this range, cin will fail.
Here's what's happening with your program:
1) You enter invalid input (such as an integer greater than 2147483647).
2) cin fails to insert the data into the variable, so it goes into a failbit state and stops accepting input.
3) Since your loop condition ALWAYS evaluates to true, and you have supplied no way for cin to recover from its failbit state, the program gets stuck in a loop that does exactly nothing.
Edit: Did you even try one of the examples that I provided earlier?