我是C语言的新手,所以请耐心等待。我试图读取一个包含字符串的文件,但获得的输出是单个字符。
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#define CALLOC(num, type) ((char*)calloc (num, sizeof(char)))
#define FREE(addr) (free((void*) (addr)))
int i, count;
char *x, *y, *z;
int main (void)
{
FILE *stream;
if ( (stream = fopen ( "test.txt", "r" )) == NULL )
{ printf ("Cannot read the new file\n");
exit (1);
}
count = 3;
x=CALLOC(count, char);
y=CALLOC(count, char);
z=CALLOC(count, char);
for ( i=0; i<count; i++ )
{ fscanf (stream,"%c %c %c", &x[i], &y[i], &z[i]);
printf ("\n %d %c %c %c ", i, x[i], y[i], z[i]);
}
FREE(x);
FREE(y);
FREE(z);
fclose (stream);
}
输入test.txt文件包含
1 ab 1
2 aa 5
1 cc 1
当前输出
0 1 a b
1 1 2
2 a a
预期输出
0 1 ab 1
1 2 aa 5
2 1 cc 1
我怀疑是否应该使用字符数组,但它似乎不起作用,我觉得使用char读取int是可以接受的。在这里,我需要预期的输出,对此,任何方法/建议都表示赞赏。
答案 0 :(得分:3)
%c
只读入一个字符。因此,它不会将ab
作为单个字符读取。您的文件行和格式不能正确读取整行。
一种简单的方法是使用fgets()
并打印整行:
char line[256];
i = 0;
while(fgets(line, sizeof line, stream))
{
printf ("%d %s", i, line);
i++;
}
顺便说一下,calloc
和free
的宏是不必要的。他们真的不会比直接使用这些功能更容易阅读代码。
答案 1 :(得分:0)
问题是你有扫描文件。 %c读取8位值。您扫描了3个字符,但该文件包含4个字符。如果您不习惯使用x,y,z的值,我不明白为什么要使用malloc。
这是一个工作来源:
#include <stdio.h>
#include <stdlib.h>
int main() {
int count,i;
char w,x,y,z;
FILE *stream;
if((stream = fopen("test.txt","r")) == NULL) {
printf("Cannot read the new file\n");
return 1;
}
count = 3;
for(i=0;i<count;++i) {
fscanf(stream,"%c %c%c %c\n",&w,&x,&y,&z);
printf("%d %c %c%c %c\n",i,w,x,y,z);
}
return 0;
}
答案 2 :(得分:0)
for ( i=0;i<count; i++ )
{
fscanf (stream,"%s %s %s", x, y, z);
printf ("\n %d %s %s %s ", i, x, y, z);
}
您可以将循环修改为此。此循环将读取文件,直到end of file
,您必须使用%s
,因为ab
是一个字符串而不是字符,所以它不能存储在char变量中。