写入txt文件C ++

问题描述 投票:0回答:2

我想在文件中写入单词,直到我键入单词“ stop”,但是只有第一个单词被保存到文件中。有什么问题?

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;
    }
c++ file writing
2个回答
1
投票

应该是

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

如果您这样做,会更好,

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

1
投票

在这种情况下,您最好切换到以下形式的while循环:while (!file.eof())while (file.good())

除此之外,for循环必须定义变量,在您的情况下,i是未定义的,并且必须包含变量的范围,并且必须不包含其他变量定义(消息中的条件一定不能位于变量内。它必须是for循环内的if条件。

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

实际上,我不确定在您的情况下它是如何编译的:)供以后参考:for循环应如下所示:for (int i; i<100; i++) {};

我希望很清楚!

© www.soinside.com 2019 - 2024. All rights reserved.