Atoi function

Hello,

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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#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.
Last edited on
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?

I am not sure what the exact problem is but here is my guess of what your trying to do.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#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;
}
Last edited on
Topic archived. No new replies allowed.