[英]how to properly print each element in a c string?
#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");
}
In this program, I suppose to print each element in the array, which should be ABCDE but actually it prints: 在这个程序中,我想打印数组中的每个元素,它应该是ABCDE但实际上它打印:
It seems every element is weired, how should I print it correctly? 似乎每个元素都已经过,我应该如何正确打印?
A
E
─
╒
┴
■
┌
·
Φ
8
↔
p
╘
╠
x
3
☻
The type of a
is an array of char*
, not an array of char
. 的类型的
a
是阵列char*
,而不是阵列char
。 Change to: 改成:
char a[20];
Recommend compiling at the highest warning level and treat warnings as errors. 建议在最高警告级别进行编译,并将警告视为错误。 For example:
例如:
$ 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
Check the result of fopen()
and fscanf()
to be certain the file was opened and data was read into a
before attempting to use the variables. 检查
fopen()
和fscanf()
的结果,确保文件已打开,并在尝试使用变量之前将数据读入a
。
a
is an array of 20 char
pointers . a
是一个由20个char
指针组成的数组。 I think you wanted an array of 20 chars instead 我想你想要一个20个字符的数组
char a[20];
char a[20];
FILE * fin = fopen("testtest.txt","r");
int i;
fscanf(fin,"%19s",a);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.