#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 A B C D E but actually it prints:
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. 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.
a is an array of 20 char pointers. I think you wanted an array of 20 chars instead
char a[20];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With