【问题标题】:Type errors when printing characters with printf使用 printf 打印字符时出现类型错误
【发布时间】:2014-11-29 21:08:49
【问题描述】:

我正在尝试将学生姓名保存在 char 数组中并打印第一个学生的姓名,但我的代码不起作用。我正在练习 C,所以我自己编写随机程序,需要帮助。我的代码生成以下错误:

format '%s' expects argument of type 'char *', but argument 2 has type 'int'

我对 C 很陌生。有人可以帮忙吗?

代码:

#include <stdio.h>
#include <string.h>

main(){



char StudentsName[100];
float StudentsGrades[100];
int NumStudents, i, j;

printf("How many students you want to process? ");
scanf("%d", &NumStudents);
if(NumStudents > 15){goto skip_lines_grades;}

for(i=0; i<NumStudents; i++){

    printf("\n Write the name of the student: ");
    scanf("%s", &StudentsName[i]);

}

//Prints First Student, I'M GETTING THE ERROR HERE, WHY?
printf("%s", StudentsName[0]);

goto skip_last_msg;

skip_lines_grades:;
printf("We can process 15 students for now, try again.");

skip_last_msg:;

}

【问题讨论】:

  • char 是一个字符。
  • 您的名称数组是 100 个字符的数组,而不是 100 个字符串。你想要char StudentsName[100][MAX_NAME_LEN];
  • @KarolyHorvath 有什么解决办法吗?
  • 警告中有什么不清楚的地方?您正在使用带有 char 的 char 指针 (%s) 的 printf 格式说明符。
  • StudentsName[0] 是一个字符,字符不是用 %s 打印的。

标签: c char printf


【解决方案1】:

我希望你从上面的讨论中得到了基本的想法。总而言之,您需要定义一个包含 100 个字符变量的数组。

另外,关于您的错误,对于 char StudentsName[100];,StudentsName[0] 代表第一个 char 变量值,而不是地址,正如 %s 所期望的那样。所以,你的编译器是对的。如果需要打印char,则需要使用%c 说明符。但是,考虑到您的程序逻辑,这也是错误的。

要更正,你可以

  1. 分配一个char [100] 类型的数组,用于保存多个学生的数据。

  2. 动态分配内存。

  3. 循环获取每个学生的输入。

  4. 打印输出。

  5. 释放分配的内存。

检查修改后的代码,不言自明。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define NAMESIZ 128

int main(){



char *StudentsName[100];   //notice here
float StudentsGrades[100];
int NumStudents, i, j;

printf("How many students you want to process? ");
scanf("%d", &NumStudents);
if(NumStudents > 15){goto skip_lines_grades;}

for(i=0; i<NumStudents; i++){

 StudentsName[i] = malloc(NAMESIZ);                   //notice here
 printf("\n Write the name of the student: ");
 scanf("%s", StudentsName[i]);                        //notice here

}

//for(i=0; i<NumStudents; i++)   //uncomment to print all student data
i = 0;                           //comment out to print all student data
printf("Student [%d] is %s\n", (i+1), StudentsName[i]);

for(i=0; i<NumStudents; i++)
free (StudentsName[i]);                              //notice here

goto skip_last_msg;

skip_lines_grades:;
printf("We can process 15 students for now, try again.");

skip_last_msg:;


}

【讨论】:

  • 这对您来说似乎是不言自明的,但我认为通过 cmets 之外的一些实际解释会大大改善这个答案,解释 OP 一开始就做错了。
猜你喜欢
  • 1970-01-01
  • 2018-11-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多