简体   繁体   English

使用g ++进行ifstream错误但使用Visual Studio进行编译

[英]ifstream error with g++ but compiles with Visual Studio

I have been using Visual Studio for a project I am working on, though it must also compile with GCC on Linux. 我一直在使用Visual Studio来处理我正在进行的项目,尽管它也必须在Linux上使用GCC进行编译。 I have completed my project and it runs fine, but I sent the files over to my Linux shell and I receiving an error with a trivial line of code: 我已经完成了我的项目并运行良好,但我将文件发送到我的Linux shell并且我收到一个错误的代码:

std::ifstream input(s);

This gives me error saying there is no matching function. 这给了我一个错误,说没有匹配的功能。 s is an std::string by the way. 顺便说一句, s是一个std::string Can anyone enlighten me why this runs under Visual Studio but not GCC, even though I am looking at the documentation for ifstream? 任何人都可以告诉我为什么它在Visual Studio下运行而不是GCC,即使我正在查看ifstream的文档? Perhaps an old version of GCC? 也许是旧版GCC?

EDIT : GCC version is 4.2.1 The exact error is: 编辑 :GCC版本是4.2.1确切的错误是:

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

EDIT 2: Relevant code: 编辑2:相关代码:

std::string s = "";
if(argc == 2)
    s = argv[1];
else{
    std::cout << "Bad filename?" << std::endl;
    return 1;
}
std::ifstream input(s);

Download latest version of GCC, and compile your program with -std=c++0x option. 下载最新版本的GCC,并使用-std=c++0x选项编译程序。 In C++11, stream classes has constructor which takes std::string as argument, and GCC by default doesn't enable C++11, so you need to enable by providing -std=c++0x compiler option. 在C ++ 11中,流类具有构造函数,它将std::string作为参数,默认情况下GCC不启用C ++ 11,因此需要通过提供-std=c++0x编译器选项来启用。

If you cannot use C++11, then do this: 如果你不能使用C ++ 11,那么这样做:

std::ifstream input(s.c_str());

This should compile, both in C++03 and C++11. 这应该在C ++ 03和C ++ 11中编译。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM