【问题标题】:Array of strings won't print字符串数组不会打印
【发布时间】:2021-04-03 19:53:29
【问题描述】:

我正在制作一个程序,教师可以在其中输入学生人数和全名。我不知道我做错了什么,因为这是我第一次尝试打印字符串数组。这是我遇到问题的程序部分:

#include <stdio.h>

int main()
{
    int n_students,i,b=1;
    char surname[20],first_name[20];

    printf("number of students:");
    scanf("%d",&n_students);

    for(i=0;i<n_students;i++)
    {
        printf("%d. ",b);
        scanf("%s %s",&surname[i],&first_name[i]);
    }
    for(i=0;i<n_students;i++)
    {
        printf("%s, %s",first_name[i],surname[i]);
    }
}

这部分是我遇到的麻烦。请帮忙

    for(i=0;i<n_students;i++)
    {
        printf("%s, %s",first_name[i],surname[i]);
    }

【问题讨论】:

  • 你没有字符串数组,你有一个字符数组(即“一个字符串”)你的代码将覆盖名称(第一个字母除外)
  • 提示:C 中的字符串是字符数组。现在试试。
  • 您可以通过在循环中将 %s 替换为 %c 来简单地修复它。因为你不需要一个字符串数组,而是一个字符数组。

标签: arrays c for-loop scanf


【解决方案1】:

printf("%s, %s",first_name[i],surname[i]); 调用 未定义的行为,因为它正在传递 char,而 char* 是必需的。

你只有两个字符串,而不是字符串数组。

固定代码:

#include <stdio.h>

#define MAX_STUDENT_NUM 1024

int main(void)
{
    int n_students,i,b=1;
    /* allocate arrays of (arrays to store) strings */
    char surname[MAX_STUDENT_NUM][20],first_name[MAX_STUDENT_NUM][20];

    printf("number of students:");
    /* check if scanf() is successful */
    if(scanf("%d",&n_students) != 1)
    {
        fputs("number read failed\n", stderr);
        return 1;
    }
    /* check the number to avoid buffer overrun */
    if(n_students > (int)(sizeof(surname) / sizeof(*surname)))
    {
        fputs("too many students\n", stderr);
        return 1;
    }

    for(i=0;i<n_students;i++)
    {
        printf("%d. ",b);
        /* remove & and limit length to read to avoid buffer overrun */
        /* check if scanf() is successful */
        if(scanf("%19s %19s",surname[i],first_name[i]) != 2)
        {
            fputs("failed to read names\n", stderr);
            return 1;
        }
    }
    for(i=0;i<n_students;i++)
    {
        printf("%s, %s",first_name[i],surname[i]);
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-14
    • 2021-07-24
    • 2020-03-13
    相关资源
    最近更新 更多