dfdhfshdkjfh
dfdhfshdkjfh

Reputation: 23

I cannot perform some input in C

I'm very new at computer program, C is my first programming language. I learn the code from book and now I'm at the input lesson. I try to write this code in C:

#include <stdio.h>

int main()
{
    
char name[99], web_address[99], address[99];
    int age;

    printf("Insert your name: ");
    fgets(name, sizeof(name), stdin);

    printf("Your web address: ");
    fgets(web_address, sizeof(web_address), stdin);

    printf("Insert your age: ");
    scanf("%i", &age);

    printf("Insert your address for more information: ");
    fgets(address, sizeof(address), stdin);


    printf("\n-----------------------------------------------------------\n");
    printf("my name is %s", name);
    printf("My web address are %s", web_address);
    printf("my age is  %i\n", age);
    printf("and my home address are %s", address);

    return 0;
}

There is no error or warning at build log, but when I try to run this code I can't input my address in it.

Upvotes: 1

Views: 90

Answers (2)

The Programming M16A4
The Programming M16A4

Reputation: 397

What I did was create an ageChar[10] array that would store the age. Then convert it to an integer using sscanf and stored it inside of the age variable (Suggested by user3386109).

#include <stdio.h>

int main() {
    char name[99], web_address[99], address[99], ageChar[10];
    int age;

    printf("Insert your name: ");
    fgets(name, sizeof(name), stdin);

    printf("Your web address: ");
    fgets(web_address, sizeof(web_address), stdin);

    printf("Insert your age: ");
    fgets(ageChar, sizeof(age), stdin);
    sscanf(ageChar, "%d", &age);

    printf("Insert your address for more information: ");
    fgets(address, sizeof(address), stdin);


    printf("\n-----------------------------------------------------------\n");
    printf("my name is %s", name);
    printf("My web address are %s", web_address);
    printf("my age is  %d\n", age);
    printf("and my home address are %s\n", address);

    return 0;
}

Upvotes: 2

Try cleaning the buffer, do this:

#include <stdio.h>

int main()
{
    
char name[99], web_address[99], address[99];
    int age;
    char ch; //CREATE NEW VARIABLE

    printf("Insert your name: ");
    fgets(name, sizeof(name), stdin);

    printf("Your web address: ");
    fgets(web_address, sizeof(web_address), stdin);

    printf("Insert your age: ");
    scanf("%i", &age);
    while ((getchar()) != '\n');
    ch = getchar(); //CLEAN THE BUFFER

    printf("Insert your address for more information: ");
    fgets(address, sizeof(address), stdin);


    printf("\n-----------------------------------------------------------\n");
    printf("my name is %s", name);
    printf("My web address are %s", web_address);
    printf("my age is  %i\n", age);
    printf("and my home address are %s", address);

    return 0;
}

Upvotes: 0

Related Questions