【问题标题】:Struct and Pointer in C (Assigning string into struct)C中的结构和指针(将字符串分配给结构)
【发布时间】:2021-04-29 10:17:49
【问题描述】:

我是 C 新手,目前正在研究指针和结构。但似乎我在为我的结构赋值时遇到了问题。

这是我的代码:

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

运行程序:

./struct

Name: David Kohler

result: 

Birth: Age: 0, 0 David

我不明白的是,当我将 name 分配给 sp->name 时,它会立即打印出这样的意外结果。不提示输入年龄和出生。

但是当我这样跑的时候,它起作用了:

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

1997, 22 Kohler

那么,你们认为会发生什么?当我输入像 “David Kohler” 这样的全长名称而不是 “Kohler” 时,似乎不太好。

如果我想输入全名,有什么解决办法?我需要使用malloc吗?谢谢。

【问题讨论】:

标签: c string pointers struct


【解决方案1】:

格式说明符%s 跳过空格。您可以使用 fgets() 或修改您的 scanf() 格式说明符,正如 Jabberwocky 在 cmets 中指出的那样。

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

请注意,使用 fgets 您还会在缓冲区中获得换行符。

扫描:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-12-26
    • 2023-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-08
    • 1970-01-01
    相关资源
    最近更新 更多