'Writing to txt file C++

I would like to write the words in the file until I type the word "stop", but only the first word is saved to the file. What's the problem?

int main(int i)
    {
        ofstream file;
        string file_name,message;
        cout << "\nFilename: ";
        cin >> file_name;
        cout << "Write 'stop' to end writig to file" << endl;
        for(i=0; message!="stop"; i++)
        {
            cout << "\nYour message: ";
            cin >> message;
            file.open(file_name.c_str());
            file << message.c_str() << "\t" ;
        }
        file.close();
        return 0;
    }


Solution 1:[1]

In this case, you better switch to a while loop of the form: while (!file.eof()), or while (file.good()).

Apart from that, the for loop has to define the variable, in your case i is undefined, and must contain the range of the variable and no other variable definition (condition on message must not be inside it. It has to be an if condition inside the for loop).

   ...
   char word[20]; // creates the buffer in which cin writes
   while (file.good() ) {
        cin >> word;
        if (word == "stop") {
           break;
        ...
        }
   } 
   ...

Actually, I am not sure how it compiles at all in your case :) For future reference: for loop should look like this: for (int i = 0; i<100; i++) {};

I hope it is clear!

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1