簡體   English   中英

將字符串附加到 C++ 中的文本文件

[英]Appending strings to text files in C++

C++ 初學者,我正在嘗試 append 一些文本到預先編寫的.txt 文件中,其中每一行都有一個單詞。 我一直在使用ofstreamifstream的方法,如下所示,但每次我嘗試寫一些東西時,它都會擦除文件。 (我不允許使用ios:app或類似的)

int append_new_word() {
//First I read everything on the list and save it to a string called Words_in_List

    ifstream data_wordlist_in("woerterliste"); //Opens the txt file
    if (!data_wordlist_in) // checks if the file exists
    {
        cout << "File does not exist!" << endl;
        return 1;
    }

    string Word;
    int line = 0;
    string Vorhandene_Woerter;
    std::getline(data_wordlist_in, Wort);
    do { //line counter, goes through all lines and save it to a string
        line++; 
        std::getline(data_wordlist_in, Word);
        Words_in_List = Words_in_List + "\n" + Word;
        
    } while (!data_wordlist_in.eof());

        cout << Words_in_List << endl;

        data_wordlist_in.close();

    //HEre it should save the string again in the list word per word with the neu appended word

    ofstream data_wordlist_out("woerterliste"); //opens ofstream
        if (!data_wordlist_out)
        {
            cout << "File does not exist!" << endl;
            return 1;
        }
        string new_word_in_list;
        cout << "\n Insert a Word to append: ";
        cin >> new_word_in_list;
        
        data_wordlist_out << Words_in_List << endl << new_word_in_list;

        
    data_wordlist_out.close(); //closes ofstream
}

每次我嘗試打開我的程序時,它都會刪除列表。

您的代碼有一些小問題,但沒有與您的描述相符的問題。

它執行基於行的輸入,這很奇怪,因為問題描述中沒有任何內容表明有必要一次讀取一行。

它計算行數,同樣沒有明顯的原因。

它跳過了第一行(也許這是故意的,但如果是這樣的話你沒有提到)。

循環終止不正確(請參閱評論中的鏈接)。

function 被聲明為返回一個int但沒有返回。

這里有一些代碼可以解決這些問題。 它讀取字符而不是行(使用get() ),這使得讀取輸入更簡單,但本質上它與您的代碼是相同的技術。

void append_new_word()
{
    string existing_content;
    ifstream in("file.txt");
    char ch;
    while (in.get(ch))
        existing_content += ch;
    in.close();
    cout << "enter a new word ";
    string new_word;
    cin >> new_word;
    ofstream out("file.txt");
    out << existing_content << new_word << '\n';
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM