首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

请问 c_str() 有什么用

2013-04-07 
请教 c_str() 有什么用书上说,好像string对象就是指针(是不是可以这么说?)比如 const char hello[] { H

请教 c_str() 有什么用
书上说,好像string对象就是指针(是不是可以这么说?)
比如 
const char hello[] = { 'H', 'e', 'l', 'l', 'o', '\0' };
string s=hello;

但是


#include<fstream>
#include<string>
using namespace std;
int main()
{
    string x("in.txt");
    ifstream infile(x);//为什么这里出错?
    ofstream outfile("out.txt");

    string s;

    while (getline(infile, s))
        outfile << s << endl;
    return 0;
}

为什么这里一定要写x.c_str()?
ifstream infile(x.c_str());

ps (那个程序在vs里能通过,在codeblocks里不能通过。。。)
[解决办法]
这个好理解呀,因为istream没有提供参数为 const string类构造函数,而提供了char*为参数的构造函数
如果VS里能行,就证明VS里提供了数为 const string类构造函数;

我给你讲一次,你哪里理解错了
const char hello[] = { 'H', 'e', 'l', 'l', 'o', '\0' };
string s=hello;

在这里hello是指向“hello”的指针
而s就是一个string,不是什么指针
string s=hello,这语句的意思就是用const char* 的hello指针构造函数构造一个string

而不是简单的赋值!!!!!!!!!!!!!!!!!!!!!

热点排行