I posted this code for a user who needed help on these forums. But I try this codes on my compiler, and it doesn't works. But I have tried that same dang code in other application, and it works just fine. Does someone knows what the heck is going on with it?
Thanks in advance. :)
The program asks the user to type an integer, and it converts a string to a integer.
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
int main() {
char age[10];
int intr = atoi ( age );
cout << "How old are you?" << endl;
cin >> age;
//If the user typed an invalid number or a negative number shows a message
if ( age[0] == 0 ){
cout << "\a" << "You typed an invalid number" << endl << endl;}
if ( age[0] <= '0' ) {
cout << "\a" << "You typed an invalid number" << endl << endl;}
else
{
cout << "You have " << intr << " years old\n\n";
}
//Prevents the program to close after the user types his/her age
system("PAUSE");
return 0;
}
The problem is that the if function is not taking any action, (if age[0] == 0).
If the user typed an invalid number, the program should show a message.
Why you have converted the age to integer prior to user input?
I think you have accidently written the same above........
char age[10];
/// int intr = atoi ( age );
cout << "How old are you?" << endl;
cin >> age;
int intr = atoi ( age ); /// this should be here after user input.
By the way I am not able to get ur problem.
Can u please specify in which compiler it works fine and in which it doesn't?
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
int main()
{
char age[10];
cout << "How old are you?" << endl;
cin >> age;
int enteredAge = atoi ( age );
if ( enteredAge <= 0 )
{
cout << "\a" << "You entered an invalid age" << endl << endl;
}
else
{
cout << "You are " << enteredAge << " years old\n\n";
}
//Prevents the program to close after the user types his/her age
system("PAUSE");
return 0;
}