为什么我应该在函数中使用c_str() [英] Why should I use c_str() in functions

查看:168
本文介绍了为什么我应该在函数中使用c_str()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读C ++ Primer这本书,并在它使用的文件输入输出章节:

  ifstream infile(ifile.c_str ()); 

以打开名称为 ifile



我尝试了代码,即使没有 c_str() / strong>那么使用它的意义是什么?



应该使用 c_str()我试图从命令行参数打开一个文件?我的意思是这是正确的用法:

  ifstream fin(argv [1])$ ​​b $ b  

  ifstream fin(argv [1] .c_str())


ifstream 的构造函数只使用一个 const char * (这是 c_str()方法提供的。



我相信有一个新的构造函数在即将到来的标准中使用 std :: string (编辑)参见此答案



它也可能是您的实现。


I am reading the book C++ Primer and at the file input output chapter it uses:

ifstream infile(ifile.c_str());

to open a file whose name is in the string ifile.

I tried the code and it works perfectly even without c_str(). So what is the point of using it?

Should I use c_str() when I am trying to open a file from a command line argument? I mean which is the correct usage:

ifstream fin( argv[1] )

or

ifstream fin( argv[1].c_str() )

解决方案

The constructor for ifstream used to only take a const char * (which is what the c_str() method provides.

I believe that there is a new constructor for it that takes a std::string in the upcoming standard, (edit) see this answer.

It could also be specific to your implementation.

这篇关于为什么我应该在函数中使用c_str()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆