Hello,
I've been wondering.
I'd like to understand how inputs are handled.
Let's say I want receive an integer.
we have
int age;
I want user to input his age, and the process this integer.
cin>>age;
But what if user isn't smart enough and enters something different, like character('a'), or string("aaa")?
Can I control the flow of the program to go back to the point of inputing the age, to prevent this type of error?
Now, since I don't know the answer to above(I'd like to), I have to find another way.
So I create
char preAge[10];
a nice string to let user input whatever he wants to. Than, I'd convert it to int with atoi.
Now, code would look like this
1 2 3 4 5
|
do{
cin.getline(preAge, 9);
}while( !atoi(preAge) )// atoi returns 0 if it's not an integer
age = atoi(preAge);
cout<<"You are "<<age<<" years old!";
|
Great. But yet there are even more possible problems:
1) If it's not an age, but some other data with which I'm using this method, than user can't insert 0, since program would think that it's a bug.
2)If user wants to use a string longer than 9 characters... Than what happens?
I think that I should use try..catch, but I don't know how.
I wanted to test it with this simple program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
#include <iostream>
#include <stdlib.h>
using namespace std;
int main() {
char test[4];
cout<<"I'm waiting"<<endl;
cin.getline(test, 4);
cout<<atoi(test);
cin.getline(test, 4);
cout<<test;
cin.get();
return 0;
}
|
Now, in this program, if I enter a string longer than 3 characters, than my program would show only 3 characters(as a number), and then return 0(without getting another input nor printing it in unchanged form). I guess that some exception is thrown, but again, I don't know which.
How should I try to solve these problems? Should I try to use string instead of integers and then convert them when I'm sure?
How should I create program to be free from problems when user enters too long string?