简体   繁体   English

写入txt文件C++

[英]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.我想在文件中写入单词,直到我输入单词“stop”,但只有第一个单词被保存到文件中。 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()) .在这种情况下,您最好切换到以下形式的 while 循环: while (.file.eof())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).除此之外,for循环必须定义变量,在你的情况下,我是未定义的,并且必须包含变量的范围并且没有其他变量定义(消息的条件不能在其中。它必须是一个if条件在for循环内)。

   ...
   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++) {};实际上,在您的情况下,我完全不确定它是如何编译的:) 供将来参考: for循环应如下所示: for (int i = 0; i<100; i++) {};

I hope it is clear!我希望这很清楚!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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