c++ - 将字符串放入 ifstream 方法中

标签 c++ string file-io input ifstream

<分区>

我正在学习 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,这表明语法中有错误,但是语法中有什么错误呢?谢谢!

最佳答案

您应该将 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 !!!
}

关于c++ - 将字符串放入 ifstream 方法中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1159100/

相关文章:

c++ - 空指针代替 int 类型的指针

c++ - 空字符串加一个整数?

c++ - 使用 OpenCV 最小化方程中的矩阵

c++ - 为什么 std::string 上的 Sizeof 运算符会产生意外结果?

c++ - 如何将一串十六进制值转换为字符串?

c++ - 将矩阵写入文件

java - 在java中对二维数组进行排序

C++ 高阶函数

python - 如何判断一个字符串是否只包含字母和空格

android - 将文件保存在 Nexus 7 的外部存储器上并从 PC 检索