我有一个用文字写的数字文本文件,其间的空格如...
零三五二一..等等总共有3018个字。
这是我的代码:
#include <stdio.h>
int main(void)
{
int i = 0;
int d = 0;
int j = 0;
char array[9054][5];
char hi[9054];
FILE *in_file;
in_file = fopen("message.txt", "r");
while (!feof(in_file))
{
fscanf(in_file, "%s", array[i]);
i++;
}
printf(array[9049]);
while (1);
return 0;
}
所以在我的文本文件中第9049个值是第三个..但是当我运行这个脚本时,它打印“threethreezero”而不是?我认为fscanf忽略了空格(空格)所以为什么接受另外三个零而不是这个字符串?
答案 0 :(得分:1)
OP在评论的帮助下解决问题,所以这是一个累积修复。
#include <stdio.h>
int main(void)
{
int i = 0;
int d = 0;
int j = 0;
// Make room for the null character
char array[9054][5+1];
char hi[9054];
FILE *in_file;
in_file = fopen("message.txt", "r");
//check `fscanf()`'s return value rather than using feof()
// Limit input put with 5
while (fscanf(in_file, "%5s", array[i]) == 1);
i++;
}
// Check that code read enough input
if (i >= 9049) {
// Do not use `printf()` on uncontrolled strings that may contain %
fputs(array[9049], stdout);
} else {
puts("Oops");
}
while (1);
return 0;
}