简体   繁体   English

C 中的结构和指针(将字符串分配给结构)

[英]Struct and Pointer in C (Assigning string into struct)

I'm new to C and i currently studying about pointer and struct .我是 C 的新手,我目前正在研究指针和结构 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.我不明白的是,当我将 name 分配给sp->name时,它会立即打印出这样的意外结果。 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" .当我输入像“David Kohler”这样的全长名称而不是“Kohler”时,似乎不太好。

What's the solution if i want to enter a full name?如果我想输入全名,解决方案是什么? Do i need to use malloc?我需要使用 malloc 吗? Thank you.谢谢你。

Format specifier %s skips spaces.格式说明符%s跳过空格。 You can use fgets() or modify your scanf() format specifier, as Jabberwocky pointed in the comments.正如 Jabberwocky 在评论中指出的那样,您可以使用fgets()或修改您的scanf()格式说明符。

fgets: 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.请注意,使用fgets您还可以在缓冲区中获得换行符。

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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM