我的算法只是将第一个单词写入文件?

时间:2013-09-20 15:30:38

标签: c++ file

我已编写此代码以写入c ++中的文件;

string Text;
ofstream Write_Test;("Write_Test.txt"); //Creating the file

Write_Test.open("Write_Test");  //Opening it for writing to, the ios::trunc at the end means it will open the file if it already exists, and overwrite any existing data with the new data.
while (Write_Test.is_open())
{
     Write_Test << Text;    //Write a message to the file.
}

Write_Test.close(); //Close the stream, meaning the file will be saved.
cout << "Done!";

但问题是它只是将字符串的第一个单词写入文件...

所以说如果我将变量'Text'分配给我的名字'Callum Holden',它只是将Callum写入文本文件?

有人能指出我正确的方向吗?

1 个答案:

答案 0 :(得分:1)

就这么简单:

#include<fstream>
#include<iostream>
using namespace std;

int main()
{
    string Text = "text";
    ofstream Write_Test("Write_Test.txt");//Creating the file

    Write_Test << Text;   //Write a message to the file.
    Write_Test.close();   //not necessary in this case   
    if ( Write_Test.good() )
        cout << "Done!" << endl;
    else            
        cerr << "Not done!";
}