将字符串(string)采用fstream的方式写入txt

将字符串(string)采用fstream的方式写入txt

在一次偶然的机会采用了fstream将字符串写入txt中,发现将“string”直接写入没有问题,但是string str=”string”,再将str写入就出现了编译报错的情况,最后采用str.data的方式成功写入了字符串。

代码块

代码,例如:

#include 
#include 
#include    
using namespace std;
int main()
{  
    int a=0, b=6;  static string Str="abcdefg";   
    fstream fout("C://Users//lvyan//Desktop//testfile123.txt",ios::out);     //创建一个data.txt的文件
    fout << a ;  //将变量的值写入文件
    fout<< Str.data();
    fout<< b ;
    fout.close();                  //关闭文件
    //system("pause");
    return 0;
}

你可能感兴趣的:(C++)