在 C++ 的文本文件中添加更多单词

Add more words to a text file in C++

本文关键字:添加 单词 文件 C++ 文本      更新时间:2023-10-16

我正在创建一个程序,该程序将用户输入的单词写入已经有其他单词的文本文件。 所以像这样:

"words.txt"
apples
oranges
bananas

我想做的是将其他单词添加到列表中,然后在屏幕上输出所有单词。 我写了一个程序,但它不会输入用户指定的单词。

int main(){
    ifstream fin("wordlist.txt");
    if (fin.fail()){
        cerr << "Error opening the file" << endl;
        system("pause");
        exit(1);
    }
    vector<string> wordlist;
    string word;
    string out_word;
    cout << "Please enter a word: ";
    cin >> out_word;
    fin >> out_word;    //Trying to input the user specified word
    //This inputs all the words
    while (!fin.eof()){
        fin >> word;
        wordlist.push_back(word);
    }
    //This outputs all the words on the screen
    for (int i = 0; i < wordlist.size(); i++){
        cout << wordlist[i] << endl;
    }
    fin.close();
    system("pause");
    return 0;
}

处理此问题的简单方法:

  1. 将文件读入向量
  2. 询问用户单词并添加到向量中
  3. 将向量的所有单词写出到外流。