字符串数组将不会打印 [英] Array of strings won't print

查看:56
本文介绍了字符串数组将不会打印的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm making a program where a teacher can enter the number of students and their full name. I don't know what I'm doing wrong because this is the first time I'm trying to print an array of strings. This is the part of my program that I'm having trouble with:

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

这部分是我遇到的麻烦.请帮助

this part is what Im having trouble with. pls help

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

推荐答案

printf(%s,%s",first_name [i],surname [i]); 调用未定义行为,因为它传递了 char ,其中需要 char * .

printf("%s, %s",first_name[i],surname[i]); invokes undefined behavior because it is passing char where char* is required.

您只有两个字符串,而不是字符串数组.

You have only two strings, not array of strings.

固定代码:

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

这篇关于字符串数组将不会打印的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆