【问题标题】:Put A String In A ifstream Method [duplicate]将字符串放入 ifstream 方法中[重复]
【发布时间】:2009-07-21 13:15:37
【问题描述】:

我正在学习 C++,当我尝试在 ifstream 方法中使用 String 时遇到了一些麻烦,如下所示:

string filename;
cout << "Enter the name of the file: ";
   cin >> filename;
ifstream file ( filename );

这里是完整的代码:

// obtaining file size
#include <iostream>
#include <fstream>
using namespace std;

int main ( int argc, char** argv )
{
    string file;
    long begin,end;
    cout << "Enter the name of the file: ";
       cin >> file;
    ifstream myfile ( file );
    begin = myfile.tellg();
    myfile.seekg (0, ios::end);
    end = myfile.tellg();
    myfile.close();
    cout << "File size is: " << (end-begin) << " Bytes.\n";

    return 0;
}

这里是Eclipse的错误,方法前的x

no matching function for call to `std::basic_ifstream<char, std::char_traits<char> >::basic_ifstream(std::string&)'

但是当我尝试在 Eclipse 中编译时,它会在方法前放置一个 x,这表示语法错误,但语法有什么问题?谢谢!

【问题讨论】:

  • 您能否提供有关您遇到的错误的更多详细信息?或者,也许您可​​以发布一个完整的示例......
  • 也许 fstream 不包括在内?请提供完整代码
  • 您是否包含了正确的标题?

标签: c++ string file-io input ifstream


【解决方案1】:

您应该将char* 传递给ifstream 构造函数,使用c_str() 函数。

// includes !!!
#include <fstream>
#include <iostream>
#include <string>
using namespace std;

int main() 
{   
  string filename;
  cout << "Enter the name of the file: ";
  cin >> filename;
  ifstream file ( filename.c_str() );    // c_str !!!
}

【讨论】:

    【解决方案2】:

    问题是ifstream的构造函数不接受字符串,而是c风格的字符串:

    explicit ifstream::ifstream ( const char * filename, ios_base::openmode mode = ios_base::in );
    

    并且std::string 没有隐式转换为 c 样式字符串,而是显式转换:c_str()

    用途:

    ...
    ifstream myfile ( file.c_str() );
    ...
    

    【讨论】:

      猜你喜欢
      • 2012-11-13
      • 2019-04-05
      • 2012-10-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-08
      • 2013-03-04
      • 1970-01-01
      相关资源
      最近更新 更多