简体   繁体   中英

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;
    }

It should be,

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

It would be better if you do something like,

do{
   //do stuff
   if (message == "stop")
       break;
   }while(message != "stop");

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM