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

时间:2014-11-27 08:04:36

标签: c++ file text add words

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

"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 个答案:

答案 0 :(得分:1)

处理此问题的简单方法:

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