我在ac代码中使用fscanf函数来读取包含1行由空格分隔的单词,但是例如如果第一个单词是1234,那么当我打印它时输出是234,但是其他单词在文件中读取是否正确,有什么想法吗?
FILE* file = fopen(path, "r");
char arr = getc(file);
char temp[20];
while(fscanf(file,"%s",temp)!= EOF && i<= column)
{
printf("word %d: %s\n",i, temp);
}
答案 0 :(得分:3)
char arr = getc(file);
可能上面的行导致第一个字符松散。
答案 1 :(得分:1)
char arr = getc(file);
从文件流中读取第一个字符并迭代文件流 file
答案 2 :(得分:1)
这是发布的代码,带有我的评论
When asking a question about a run time problem,
post code that cleanly compiles, and demonstrates the problem
FILE* file = fopen(path, "r");
// missing check of `file` to assure the fopen() was successful
char arr = getc(file);
// this consumed the first byte of the file, (answers your question)
char temp[20];
while(fscanf(file,"%s",temp)!= EOF && i<= column)
// missing length modifier. format should be: "%19s"
// 19 because fscanf() automatically appends a NUL byte to the input
// 19 because otherwise the input buffer could be overrun,
// resulting in undefined behaviour and possible seg fault event
// should be checking (also) for returned value == 1
// this will fail as soon as an `white space` is encountered
// as the following call to fscanf() will not read/consume the white space
// suggest a leading space in the format string to consume white space
{
printf("word %d: %s\n",i, temp);
// the variable 'i' is neither declared nor modified
// within the scope of the posted code
}