我是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 是可以接受的。在这里我需要预期的输出,为此任何方法/建议都是值得赞赏的。
最佳答案
%c
只读取一个字符。所以它不会将 ab
读取为单个字符。您在文件中的行和您的格式无法正确读取整行。
一个简单的方法是使用 fgets()
并打印整行:
char line[256];
i = 0;
while(fgets(line, sizeof line, stream))
{
printf ("%d %s", i, line);
i++;
}
顺便说一下,calloc
和free
的宏是不必要的。与直接使用这些函数相比,它们并没有使代码更易于阅读。
关于c - 从 C 文件中读取字符串和整数的组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31536689/