2014-06-07 21 views
-3

我有一个菜单,根据用户的选择启动一些方法。然而,其中两种方法无法正常工作,我不知道为什么。 这对他们来说是菜单的一部分:C++不能读取文件并追加给出奇怪的结果

case 2: 
{ 
    string fileName; 
    cout << "Which file to read?:"; 
    cin>>fileName; 
    this->ReadFromFile(fileName); 
    break; 
} 
case 3: 
{ 
    string fileName; 
    cout << "Enter name for the file:"; 
    cin>>fileName; 
    this->WriteToFile(fileName); 
    break; 
} 

这里是方法:

void ReadFromFile(string file) 
    { 
     string line; 
     ifstream rfile ("FileSystem/" + file);//open file for reading 
     if (rfile.is_open()) 
     { 
      while(getline(rfile, line)) 
      { 
       cout << line << endl; 
      } 
     } 
     else 
     { 
      cout << "An error occurred when tried to read from this file." << endl; 
     } 
     rfile.close(); 
     _getch(); 
    } 

    void WriteToFile(string fileName) 
    { 
     ofstream myFile; 
     ifstream exists (fileName);//open read stream to check if file exists 
     if(exists)//returns true if file can be opened and false if it cant 
     { 
      exists.close();//close the stream 
      myFile.open(fileName, ios_base::app);// open file for reading(ostream) 
     } 
     else 
     { 
      exists.close(); 
      CreateFile(fileName);//file doenst exists, so we create one and list it in the file tree 
      myFile.open("FileSystem/" + fileName, ios_base::app);// open file for reading(ostream) 
     } 
     if(myFile.is_open()) 
     { 
      string input; 
      cout << "start writing and press enter to finish. It will be done better later." << endl; 
      cin>>input; 
      myFile << input; 

     } 
     else 
     { 
      cout<<"An error occurred when tried to open this file."<<endl; 
     } 
     myFile.close(); 
     _getch(); 
    } 

现在这里是有趣的部分。当我尝试将某些内容写入文件时,无论如何,我都会打开它:'ios_base :: app'或'ios:app'它只是重写它。但它甚至不能做到这一点。如果我有像'希这样就是我'这样的空格的话。例如,它只写第一个单词,这里是'嗨'。 因此,如果我决定阅读该文件,首先会发生的事情是它说文件无法运行,甚至在它要求我输入名称之前。这发生在前3次尝试,然后阅读神奇的作品。 在过去的两个小时里,我已经把我的脑袋砸到了这里,我仍然无法理解发生了什么。任何人都可以向我解释这一点,并告诉我我的错误?

+0

狭窄,狭窄,狭窄!首先使用调试器! –

回答

0
​​

在上面的行中,cin>>input将在一个空格处停止读取。您应该使用std::getline。另见this answer

+0

当我使用std :: getline(std :: cin,input)时,它在按下第一个键之后停止。它不写任何东西,它也删除文件中的everthing。 –

+0

您之前的阅读操作('cin >> fileName;')不会“吃”换行符。所以getline只读取你在文件名后输入的换行符。请参阅[如何刷新cin缓冲区?](http://stackoverflow.com/q/257091/33499) – wimh

+0

谢谢,它修复了它。除此之外,我发现我试图找出该文件是否因某种原因而可能运行的方式返回了错误。无论如何,我也修正了这一点。 –