#include <stdio.h>
#include <iostream>
using namespace std;
int main(){
char *a[20];
FILE * fin = fopen("testtest.txt","r");
int i;
fscanf(fin,"%s",a);
for(i=0;i<20;i++)
{
printf("%c\n",a[i]);
}
system("pause");
}
在这个程序中,我想打印数组中的每个元素,应该是A B C D E. 但实际上它打印:
似乎每个元素都已经过,我应该如何正确打印?
A
E
─
╒
┴
■
┌
·
Φ
8
↔
p
╘
╠
x
3
☻
答案 0 :(得分:8)
a
的类型是char*
的数组,而不是char
的数组。改为:
char a[20];
建议在最高警告级别进行编译,并将警告视为错误。例如:
$ gcc -Wall -Werror -pedantic main.c main.c: In function ‘main’: main.c:9:5: error: format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘char **’ [-Werror=format] main.c:10:5: error: format ‘%c’ expects argument of type ‘int’, but argument 2 has type ‘char *’ [-Werror=format] cc1: all warnings being treated as errors
检查fopen()
和fscanf()
的结果,确保在尝试使用变量之前,文件已打开,数据已读入a
。
答案 1 :(得分:2)
a
是一个包含20个char
指针的数组。我想你想要一个20个字符的数组
char a[20];
答案 2 :(得分:0)
char a[20];
FILE * fin = fopen("testtest.txt","r");
int i;
fscanf(fin,"%19s",a);