Search code examples
promptcs50

receives a number between 0 and 120


I'm trying to get the programme to keep asking the person their age until the program receives a number between 0 and 120. I've set up a do while loop but i'm getting an error message, any help would be appreciated.

{
    string name = get_string("What's your name?\n");
    printf("Hello, %s\n", name);
    sleep(1);
do
{
    int age = get_int("How old are you?\n");
}
while (age < 1 || age > 120)

    printf("Wow, %s you've been around for atleast %i days!\n", name, age * 365); 
    sleep(1);

ERROR MESSAGE

name.c:14:8: error: use of undeclared identifier 'age'
while (age < 1 || age > 120)
       ^
name.c:14:19: error: use of undeclared identifier 'age'
while (age < 1 || age > 120)
                  ^
name.c:16:71: error: use of undeclared identifier 'age'
    printf("Wow, %s you've been around for atleast %i days!\n", name, age * 365); 
                                                                      ^
name.c:21:42: error: use of undeclared identifier 'age'
    printf("So you're %i and from %s\n", age, town);
                                         ^
4 errors generated.
<builtin>: recipe for target 'name' failed
make: *** [name] Error 1

Solution

  • Declare age outside of do:

    int age;
    do {
        age = get_int("How old are you?\n");
    }
    while (age < 1 || age > 120)