Add more words to a text file in C++

1.7k views Asked by At

I'm creating a program that writes user inputted words to a text file that already has other words to begin with. So like this:

"words.txt"
apples
oranges
bananas

what I wanna do is add other words to the list and then output all the words on the screen. I wrote a program but it won't input the user specified word.

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

There are 1 answers

2
stefaanv On

A simple way to handle this:

  1. Read in the file to the vector
  2. Ask the user words and add to the vector
  3. Write out all the words of the vector to an out-stream.