将字符串放入ifstream方法中 [英] Put A String In A ifstream Method

查看:152
本文介绍了将字符串放入ifstream方法中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习C ++,并且尝试在 ifstream 方法中使用 String 时遇到一些麻烦,例如:

I'm learning C++ and i'm getting some troubles when i'm trying to use a String in a ifstream method, like this:

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 :

And here is the error of the Eclipse, the x before the method:

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

但是当我尝试在Eclipse中进行编译时,它在方法前放置了 x ,这表明语法错误,但是语法有什么问题呢?谢谢!

But when i try to compile in Eclipse it put an x before the method, that indicates an error in the syntax, but what is wrong in the syntax? Thanks!

推荐答案

您应将 char * 传递给 ifstream 构造函数,并使用 c_str()功能.

You should pass char* to ifstream constructor, use c_str() function.

// 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 !!!
}

这篇关于将字符串放入ifstream方法中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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