加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 在ifstream方法中放置一个字符串

发布时间:2020-12-16 10:26:29 所属栏目:百科 来源:网络整理
导读:参见英文答案 No matching function – ifstream open()????????????????????????????????????1个 我正在学习C,当我尝试在ifstream方法中使用String时,我遇到了一些麻烦,如下所示: string filename;cout "Enter the name of the file: "; cin filename;ifst
参见英文答案 > No matching function – ifstream open()????????????????????????????????????1个
我正在学习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 !!!
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读