首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >F不读第一个单词的第一个字符(在c中)

F不读第一个单词的第一个字符(在c中)
EN

Stack Overflow用户
提问于 2015-10-19 17:03:57
回答 4查看 1.6K关注 0票数 1

我在c代码中使用fscanf函数读取一个文件包含一行由空格分隔的单词,但是例如,如果第一个单词是1234,那么当我打印它时输出是234,但是文件中的其他单词被正确读取,有什么想法吗?

代码语言:javascript
代码运行次数:0
运行
复制
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);
}
EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2015-10-19 17:31:32

这是贴出的代码和我的评论

代码语言:javascript
代码运行次数:0
运行
复制
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
}
票数 1
EN

Stack Overflow用户

发布于 2015-10-19 17:05:57

char arr = getc(file);

可能是线上引起了第一个字符的松动。

票数 3
EN

Stack Overflow用户

发布于 2015-10-19 17:06:08

代码语言:javascript
代码运行次数:0
运行
复制
char arr = getc(file);

从文件流中读取第一个字符并迭代文件流文件。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/33220038

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档