Varible 2020-03-22 18:20 采纳率: 75%
浏览 349
已采纳

C/C++ 用feof函数,输出时怎么把最后的一个字符重复输出了?

C版

#include <stdio.h>
#include <errno.h>
#include <ctype.h>
int main(int argc,char **argv) {
 FILE *input = fopen("in.test.txt","r");
 char c = '\0';
 while (! feof(input)) {
  fscanf(input,"%c",&c);
  printf("%c",tolower(c));
 }
 printf("\b\n");
 return 0;
}
/*
 * in.test.txt: "XXX"
 * OutPut: "xxxx"
*/

C++版

#include <cstdio>
#include <cerrno>
#include <cctype>
using namespace std;
int main(int argc,char **argv) {
 FILE *input = fopen("in.test.txt","r");
 char c = '\0';
 while (! feof(input)) {
  fscanf(input,"%c",&c);
  printf("%c",tolower(c));
 }
 printf("\b\n");
 return 0;
}
/*
 * in.test.txt: "XXX"
 * OutPut: "xxxx"
*/

求助大佬们为什么会最后一个字符输出两次?

  • 写回答

1条回答 默认 最新

  • threenewbee 2020-03-22 21:04
    关注
    #include <cstdio>
    #include <cerrno>
    #include <cctype>
    using namespace std;
    int main(int argc,char **argv) {
     FILE *input = fopen("c:\\in.test.txt","r");
     char c = '\0';
     while (1) {
      if (fscanf(input,"%c",&c) == EOF) break;
      printf("%c",tolower(c));
     }
     printf("\b\n");
     return 0;
    }
    

    scanf失败,c还是之前的值,所以多输出1个字符。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 手机连接电脑热点显示无ip分配
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大