2013-02-11 81 views
2

在C++中,我目前正在學習如何使用ofstream寫入一個文件(我們假設是一個txt文件),然後我決定編寫自己的小代碼並自己嘗試。我有一個關於我的代碼的問題,因爲它沒有按照我的意圖運行。使用'ofstream'代碼寫入文本文件錯誤

#include <iostream> 
#include <fstream> 
using namespace std; 

int main() { 
    char opt; 
    cout<<"Would you like to write to a new/existing file? [Y/N]\n"; 
    cin>>opt; 

    if(opt=='Y'||opt=='y') { 
     ofstream file; 
     char filename[50]; 
     char statement[55]; 
     cout << "Please enter the name of the file you wish to open:\n"; 
     cin.getline(filename, 50); 
     file.open(filename); 
     cout << "Please enter the text you wish to be written on the file:\n"; 
     cin.getline(statement, 55); 
     file << statement; 
     file.close(); 
    } 
    else { 
     return 1; 
    } 
    return 0; 
} 

在代碼中,我問用戶他們是否要寫入文件。如果他們輸入Y,它將進入'if語句'並執行代碼,但是如果他們輸入N(或其他),它將會失敗。我的問題是,每當我選擇說'Y'並嘗試寫入文件時,它不會讓我'cin'文件名後 cout<<"Please enter the name of the file you wish to open:\n";。它立即要求輸入要寫入文件的文本。只有當我使用if語句並詢問用戶是否想寫入文件時纔會出現此錯誤。如果我刪除'if語句'並將'if語句'中的代碼寫入主體本身而不給用戶輸入Y或N的選項,則代碼工作正常。所以我知道這不是if語句中的代碼中的錯誤,它與我理解這些代碼應該如何工作的概念有關。請原諒我的愚蠢,有一些明顯的我失蹤,但我似乎無法找到原因。

SOLUTION:任何人誰有同樣的問題,所有你需要做的就是cin.ignore();cin.getline();後。

+0

http://stackoverflow.com/search?q=getline+skipping – chris 2013-02-11 23:54:36

回答

0

可以使用ofstream的here的寫入方法例如