C ++ fstream无法正常工作

时间:2015-02-04 22:40:12

标签: c++ fstream

此程序正在执行而不会出现任何错误。但似乎没有任何东西从test.txt写入或读取。

请帮我发现错误。我觉得我已正确实现了ofstream和ifstream。我无法发现我错过的东西。

#include <iostream>
#include <fstream>

using namespace std;


int main(int argc, const char * argv[]) {

   ofstream fout;
   ifstream fin;
   string s;
   cout<<"Enter a string: ";
   getline(cin,s);

   fout.open("test.txt");
   if(fout.is_open())
   {
      fout<<s;
      fout.close();
   }
   else
   {
      cout<<"Error ";
   }

   fin.open("test.txt");

   if(fout.is_open())
   {
      while(getline(fin,s))
      {
         cout<<"here";
         cout<<s<<endl;
      }
      fout.close();
   }

   return 0;
}

1 个答案:

答案 0 :(得分:3)

if(fout.is_open()) { // <<< should be fin
    while(getline(fin,s)) {
        cout<<"here";
        cout<<s<<endl;
    }

    fout.close(); // <<< also fin is needed here!
}

您在代码中混淆了finfout

请查看固定版本here(注意我刚刚使用了预定义的字符串而不是用户输入):

fin.open("test.txt");
if(fin.is_open()) {
    while(getline(fin,s)) {
        cout<<"here";
        cout<<s<<endl;
    }
    fin.close();
}