2014-06-07 17 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

謝謝,它修復了它。除此之外,我發現我試圖找出該文件是否因某種原因而可能運行的方式返回了錯誤。無論如何,我也修正了這一點。 –