zoukankan      html  css  js  c++  java
  • C++的ifstream中使用eof最后一个字符输出两次,其实不是eof的锅!

    写C++文件输入输出流时遇到的小问题

    当我执行以下代码时,最后的值会打印两次:

     1 #include <iostream>
     2 #include <stdlib.h>
     3 #include <fstream>
     4 using namespace std;
     5 
     6 int main(void)
     7 {
     8         int a = 0,b = 1,c = 2,d = 3;
     9         char ch;
    10         ofstream FileOpen("Test.txt");
    11         FileOpen<<"HelloWorld!
    ";
    12         FileOpen<<a<<b<<c<<d;
    13         FileOpen.close();
    14         ifstream Filein("Test.txt");
    15         while(!Filein.eof())
    16         {
    17                 Filein.get(ch);
    18                 cout<<ch;
    19         }
    20         Filein.close();
    21         cout<<endl;
    22         system("pause");
    23         return 0;
    24 }

    问题在于get()方法:get()方法返回当前文件“内置指针”指向的下一个字符,然后再将“内置指针”向后移动。

    也就是说“内置指针”是在执行完get()后才指向下一个字符。

    下面来分析一下波:

    当“内置指针”指向c时,get()返回d的值给ch,然后“内置指针”向后移动指向d,打印d的值,此时eof()返回false,而循环继续进行;

    再次get(),当前“内置指针”指向d,返回的是d后面的值,然而d后面是EOF,读取失败,无法赋值给ch,ch依然为d的值,再次打印了一次d的值,get()完后,“内置指针”指向了EOF,eof()返回true,则退出而循环。

    结束。

    原理已经懂了,进行以下的改造即可输出正确:

     1 #include <iostream>
     2 #include <stdlib.h>
     3 #include <fstream>
     4 using namespace std;
     5 
     6 int main(void)
     7 {
     8         int a = 0,b = 1,c = 2,d = 3;
     9         char ch;
    10         ofstream FileOpen(“Test.txt”);
    11         FileOpen << "Helloworld!
    ";
    12         FileOpen << a << b << c << d;
    13         FileOpen.close();
    14         ifstream Filein("Test.txt");
    15         if(Filein.get(ch),!Filein.eof())
    16         {
    17               cout << ch;
    18         }
    19         cout << endl;
    20         system("pause");
    21         return 0;
    22 }

  • 相关阅读:
    css
    常见属性
    表单
    html的块
    常见标签(一)
    html5 文本内容
    整数的分解
    快速排序及其应用
    javascript之动画特效
    html标签积累
  • 原文地址:https://www.cnblogs.com/JaxesZ/p/9906408.html
Copyright © 2011-2022 走看看