繁体   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