我在c代码中使用fscanf函数读取一个文件包含一行由空格分隔的单词,但是例如,如果第一个单词是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);
}
发布于 2015-10-19 09:31:32
这是贴出的代码和我的评论
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
}
发布于 2015-10-19 09:05:57
char arr = getc(file);
可能是线上引起了第一个字符的松动。
发布于 2015-10-19 09:06:08
char arr = getc(file);
从文件流中读取第一个字符并迭代文件流文件。
https://stackoverflow.com/questions/33220038
复制相似问题