0

I'm new to C and i currently studying about pointer and struct. But it seems like i have a problem when assigning value into my struct.

This is my code:

#include <stdio.h>

typedef struct
{
    char name[30];
    int age;
    int birth;
}
student;

void record(student *sp);

int main(void)
{
    student std1;
    record(&std1);
    
    printf("%i, %i %s\n", std1.birth, std1.age, std1.name);
}

void record(student *sp)
{
    printf("Name: ");
    scanf("%s", sp -> name);
    printf("Birth: ");
    scanf("%i", &sp -> birth);
    printf("Age: ");
    scanf("%i", &sp -> age);
}

Run program:

./struct

Name: David Kohler

result: 

Birth: Age: 0, 0 David

What i don't understand is when i'm going to assign name into sp->name it immediatly print an unexpected result like that. It's doesn't prompt to enter age and birth.

But when I ran like this, it works:

./struct
Name: Kohler
Birth: 1997
Age: 22

1997, 22 Kohler

So, what do you guys think happen? It seems like it doesn't took very well when i'm entering a full-long name like "David Kohler" instead just "Kohler".

What's the solution if i want to enter a full name? Do i need to use malloc? Thank you.

1 Answers1

0

Format specifier %s skips spaces. You can use fgets() or modify your scanf() format specifier, as Jabberwocky pointed in the comments.

fgets:

void record(student *sp)
{
    printf("Name: ");
    fgets(sp->name,30,stdin);
    strtok(sp->name,"\n"); /* Removing newline character,include string.h */
    printf("Birth: ");
    scanf("%i", &sp -> birth);
    printf("Age: ");
    scanf("%i", &sp -> age);
}

Note that with fgets you also get a newline character in your buffer.

Scanf:

void record(student *sp)
{
    printf("Name: ");
    scanf("%29[^\n]", sp -> name); /* Added a characters limit so you dont overflow */
    printf("Birth: ");
    scanf("%i", &sp -> birth);
    printf("Age: ");
    scanf("%i", &sp -> age);
}
alex01011
  • 1,670
  • 2
  • 5
  • 17