鱼C论坛

 找回密码
 立即注册
查看: 3791|回复: 7

一段简单的代码为何报错

[复制链接]
发表于 2013-2-5 21:47:43 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
void TestWrite()
{
        fstream file;
        string s = "xx.txt";
        file.open( "test.txt", fstream::in | fstream::out | fstream::app );
        file << s <<'\n';
        file.close();
}
如题,这段简单的代码在vs 2012下就会报错,通不过编译,我查过相关的文档,说fstream 的运算符重载不支持string.其运算符重载如下:
请高手解释一下为何。

basic_ostream& operator<< (bool& val );
basic_ostream& operator<< (short& val );
basic_ostream& operator<< (unsigned short& val );
basic_ostream& operator<< (int& val );
basic_ostream& operator<< (unsigned int& val );
basic_ostream& operator<< (long& val );
basic_ostream& operator<< (unsigned long& val );
basic_ostream& operator<< (float& val );
basic_ostream& operator<< (double& val );
basic_ostream& operator<< (long double& val );
basic_ostream& operator<< (void*& val );
basic_ostream& operator<< (basic_streambuf<charT,traits>* sb );
basic_ostream& operator<< (basic_ostream& ( *pf )(istream&));
basic_ostream& operator<< (basic_ios<charT,traits>& ( *pf )(basic_ios<charT,traits>&));
basic_ostream& operator<< (ios_base& ( *pf )(ios_base&));
小甲鱼最新课程 -> https://ilovefishc.com
 楼主| 发表于 2013-2-5 22:13:08 | 显示全部楼层
貌似有好多人看过帖子了。但是没人回答我。
小甲鱼最新课程 -> https://ilovefishc.com
 楼主| 发表于 2013-2-5 22:13:58 | 显示全部楼层
我试过使用g++编译,没有问题。为何vs不行呢?
苦闷呀。
小甲鱼最新课程 -> https://ilovefishc.com
发表于 2013-2-6 00:07:37 | 显示全部楼层
不着急  静等大侠指点
小甲鱼最新课程 -> https://ilovefishc.com
发表于 2013-2-6 14:43:37 | 显示全部楼层
不晓得你说的是什么意思  
  源代码中没有string类的重载,<<  运算符就肯定不支持string呗  
你要是会写的话可以自己加在后面加个重载的语句?
小甲鱼最新课程 -> https://ilovefishc.com
发表于 2013-2-6 19:39:09 | 显示全部楼层
把string类型对象 用c_str()函数转换成C风格的字符串  
例如 你要打开一个文件名为test.txt  类型为 string 则
ifstream in;
string file_name;
in.open(file_name.c_str());
小甲鱼最新课程 -> https://ilovefishc.com
发表于 2013-2-6 19:51:18 | 显示全部楼层
  1. #include <string>
  2. #include <fstream>
  3. using namespace std;
  4. void TestWrite()
  5. {
  6.         fstream file;
  7.         string s = "xx.txt";
  8.         file.open( "test.txt", fstream::in | fstream::out | fstream::app );
  9.         file << s <<'\n';
  10.         file.close();
  11. }

  12. int main(){
  13.         TestWrite();
  14. }
复制代码
我没装2012,只有VS2010测试完整代码如下,没有问题啊
小甲鱼最新课程 -> https://ilovefishc.com
发表于 2013-2-9 11:54:14 | 显示全部楼层
应为 我真的 看不懂
小甲鱼最新课程 -> https://ilovefishc.com
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-8-8 13:22

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表