2016-11-29 81 views
0

所以我試圖做一個程序,提出問題,我回答他們,直到我選擇停止(其內部循環)。 因此,舉例來說,如果我打開該文件,它應該是這個樣子:C++輸出文件

test.txt 
First question: 1. 
Second Question: 2. 
loop 
First question: 3. 
Second question: 4. 
loop 
... 

,但我發現只有最後輸入我做。

do { 
cout<<"Enter 0 to end. \n"; 
cin >> a; 

ofstream myfile; 
myfile.open ("test.txt"); 
myfile << "First question: \n"; 
cin >> a; 
myfile << a; 
myfile << "Second question: \n"; 
cin >> b; 
myfile << b; 

myfile.close(); 
}while (a!=0); 
+0

你爲什麼要打開和關閉文件中的循環?從循環中獲取該代碼。如果您想要,也可以設置打開模式以追加。 – drescherjm

+0

我想繼續輸入數據,直到我決定停止。 – Insanebench420

+1

已經有很多類似的問題。在互聯網上搜索「stackoverflow C++文件問題答案」。 –

回答

0

我建議將問題和答案複製到文件中。

int main(void) 
{ 
    bool can_continue = true; 
    ofstream myfile("test.txt"); 
    while (can_continue) 
    { 
    std::string question; 
    std::cout << "First Question:\n"; 
    std::getline(cin, question); 
    my_file << "First Question:\n"; 
    my_file << question << "\n"; 

    std::cout << "Second Question:\n"; 
    std::getline(cin, question); 
    my_file << "Second Question:\n"; 
    my_file << question << "\n"; 

    std::cout << "\nEnter 0 to quit, any other number to continue:"; 
    int number; 
    std::cin >> number; 
    if (number != 0) 
    { 
     can_continue = false; 
    } 
    } 
    return EXIT_SUCCESS; 
} 

通過將提示覆制到終端,您的用戶可以知道是否會有輸入。

請注意,使用operator>>std::string只會導致一個單詞被讀入。您將希望使用std::getline來輸入文本,直到按下Enter。

+0

我還不夠理解繼續,而且代碼在這個問題上不起作用。 – Insanebench420

+0

對不起,我的壞。 '繼續'是一個保留字。查看我的編輯。 –

+0

EXIT_SUCCESS未在此範圍內聲明,因此我將其替換爲return 0;代碼然後工作,我可以輸入並按0,但test.txt中沒有數據 – Insanebench420

0

std :: ofstream :: open默認不附加。因此,在你的情況下,它會爲每個循環迭代創建一個帶有兩個輸入的文件,並將其覆蓋下一個。

0

問題是,每次循環運行時,都會得到一個指向文件的新指針,然後開始覆蓋已經存在的內容。

有兩種方法可以解決這個問題。

1)我強烈建議的一個,在你的循環之外做以下三個陳述。循環前的前兩個和循環後的最後一個。這仍然可以讓您根據需要多次寫入。

ofstream myfile; 
myfile.open ("test.txt"); 

myfile.close(); 

2)以追加模式打開文件。要做到這一點取代

myfile.open("test.txt"); 

myfile.open("test.txt", std::ios_base::app);