| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 1512 人关注过本帖, 1 人收藏
标题:不懂求指教关于fprintf和fscanf
取消只看楼主 加入收藏
lc5491137
Rank: 2
等 级:论坛游民
帖 子:37
专家分:70
注 册:2012-3-5
结帖率:100%
收藏(1)
已结贴  问题点数:40 回复次数:3 
不懂求指教关于fprintf和fscanf
#include<stdio.h>
#include<stdlib.h>
#define MAX 40
int main(void)
{
     FILE *fb;
     char words[MAX];
     if((fb=fopen("words", "a+"))==NULL)
     {
          fprintf(stdout, "Can't open \"words\" file.\n");
          exit(1);
     }
     puts("Enter words to add to the file; \npress the Enter key at the begining of a line to terminate.");
     while(gets(words)!=NULL && words[0]!='\0')
          fprintf(fb, "%s", words);
     puts("Flie countents");
     rewind(fb);
     while(fscanf(fb, "%s", words)==1)
          puts(words);
     if(fclose(fb)!= 0)
          fprintf(stderr, "Error closing file\n");
     return 0;
}

当我输入I am a[Enter]然后为什么需要再次键入[Enter]程序才会继续(很明确的说不是while(gets(words)!=NULL && words[0]!='\0')这段程序的问题)还有一个问题是为什么输出的结果是
I
am
a
为什么每个单词后会换行
搜索更多相关主题的帖子: void include Enter file 
2012-05-14 22:11
lc5491137
Rank: 2
等 级:论坛游民
帖 子:37
专家分:70
注 册:2012-3-5
收藏
得分:0 
回复 2楼 唯我独魔
谢谢你的回答,但是对于第一个问题我还是不懂,因为我以前做的题目中while(gets(words)!=NULL && words[0]!='\0')这段代码只要我键入Enter,就会退出while循环
下面是我以前写的程序,可以证明这一点
#include<stdio.h>
#include<string.h>
int first(char *string, int ch);
#define MAX 81
int main(void)
{
     char input[MAX];
     int ch, a;
     printf("Enter a string: ");
     while(gets(input)!=NULL && input[0]!='\0')
     {
          printf("Please enter you are looking for letters:\n");
          ch=getchar();
          a=first(input, ch);
          if(a==0)
               printf("This letter is not in the string\n");
          else
              printf("The letters you are looking for the first time the location is %d\n", first(input, ch));
          printf("Enter next string: ");
          fflush(stdin);

     }
     return 0;
}

int first(char *string, int ch)
{
     int c=0;
     while(*string)
     {
          c++;
          if(*string==ch)
          {
               return c;
          }
          string++;
     }
     return 0;
}
而且经过测试把
while(gets(words)!=NULL && words[0]!='\0')
    fprintf(fb, "%s", words);
中的fprintf(fb, "%s", words);去掉,运行后当键入Enter键就会推出while循环。
2012-05-15 12:52
lc5491137
Rank: 2
等 级:论坛游民
帖 子:37
专家分:70
注 册:2012-3-5
收藏
得分:0 
回复 4楼 唯我独魔
我的意思是为什么测试程序会在第一次键入Enter后退出while循环,而我问得的程序会在第二次键入退出。因为两个程序中的用于输入的while循环是一样的,希望你能帮我解答下,你回答我不是很看的懂。
2012-05-15 15:51
lc5491137
Rank: 2
等 级:论坛游民
帖 子:37
专家分:70
注 册:2012-3-5
收藏
得分:0 
回复 4楼 唯我独魔
谢谢你,我已经明白了。
2012-05-15 19:59
快速回复:不懂求指教关于fprintf和fscanf
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.015702 second(s), 8 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved