将字符串传递给file.open();

时间:2012-06-10 04:52:28

标签: c++ string pointers

我习惯了更高级别的语言(java,python等),这很明显。我试图将用户输入的字符串传递给cin,即要打开的文件的名称。似乎有某种指针疯狂错误,我的代码将无法编译。 我删除了一些代码以使其更清晰。

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

   string hash(string filename);

   int main(){
           cout << "Please input a file name to hash\n";
           string filename;
           cin >> filename;
           cout <<hash(filename);
           return 0;
   }


    string hash(string filename){
            file.open(filename);
            if(file.is_open()){

                   file.close();
            }

            return returnval;
    } 

这是编译时错误。

<code>
$ g++ md5.cpp
md5.cpp: In function ‘std::string hash(std::string)’:
md5.cpp:22: error: no matching function for call to ‘std::basic_ifstream<char, std::char_traits<char> >::open(std::string&)’
/usr/include/c++/4.2.1/fstream:518: note: candidates are: void std::basic_ifstream<_CharT, _Traits>::open(const char*, std::_Ios_Openmode) [with _CharT = char, _Traits = std::char_traits<char>]
</code>

(我知道有md5哈希的库,但我正在尝试了解哈希如何工作,最终哈希冲突)

1 个答案:

答案 0 :(得分:20)

open()采用C风格的字符串。使用std::string::c_str()来获取此信息:

file.open (filename.c_str());

为了只使用一个字符串,如下所述,你需要使用支持C ++ 11的编译器,因为为C ++ 11添加了重载。

它与Java等不同的原因在于它来自C. C类中不存在类(很好,不像它们在C ++中那样),更不用说String类了。为了让C ++提供一个字符串类并保持兼容性,它们需要是不同的东西,并且该类为const char * -> std::string提供了转换构造函数,并且c_str()提供了另一种方式。

考虑将参数(也可能是返回)也传递给const std::string &;没有不必要的副本优化可能会抓住这些优势,但总是很好。