首页 > 解决方案 > 写入txt文件C++

问题描述

我想在文件中写入单词,直到我输入单词“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++filewriting

解决方案


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

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

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

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

我希望这很清楚!


推荐阅读