尝试使用带有infile.open()的字符串变量在c ++中被视为char [英] Trying to use a string variable with infile.open() is treated as a char in c++
问题描述
我试图创建一个程序,用户输入一个文件名,然后程序尝试打开它,并检查它是否是打开的。我使用getline函数。这是我的代码到目前为止:
I'm trying to make a program where the user enters a file name and then the program tries opening it and checks to see if it is open. I am using the getline function. Here is my code so far:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
void readGameFile();
int main()
{
readGameFile();
return 0;
}
void readGameFile()
{
ifstream infile;
string s;
string fileName;
getline(cin,fileName);
infile.open(fileName);
if(infile.is_open())
{
cout << "It worked!"<<endl;
}
else
{
cout << "You messed up"<<endl;
}
}
它给我这个错误:
23 :22:error:没有匹配的函数调用'std :: basic_ifstream :: open(std :: string&)'
It gives me this error: 23:22: error: no matching function for call to ‘std::basic_ifstream::open(std::string&)’
23:22: :
/usr/include/c++/4.6/fstream:531:7:note:void std :: basic_ifstream< _CharT,_Traits> :: open(const char *,std :: ios_base :: openmode) _CharT = char,_Traits = std :: char_traits,std :: ios_base :: openmode = std :: _ Ios_Openmode]
/usr/include/c++/4.6/fstream:531:7:注意:没有已知的参数转换1从'std :: string {aka std :: basic_string}'到'const char *'
23:22: note: candidate is: /usr/include/c++/4.6/fstream:531:7: note: void std::basic_ifstream<_CharT, _Traits>::open(const char*, std::ios_base::openmode) [with _CharT = char, _Traits = std::char_traits, std::ios_base::openmode = std::_Ios_Openmode] /usr/include/c++/4.6/fstream:531:7: note: no known conversion for argument 1 from ‘std::string {aka std::basic_string}’ to ‘const char*’
所以,我不确定是什么问题。我是相当新的编程,我试图找出一个类项目(这不是任务,它只是一个通用版本的问题,我在我的项目到目前为止)。如果你能给任何帮助,那将是巨大的。谢谢!
So, I'm not really sure what the problem is. I'm fairly new to programming, I'm trying to figure this out for a class project(this isn't the assignment, it's just a generic version of the problem I'm having in my project so far). If you can give any help, that would be great. Thanks!
推荐答案
open
:
void open( const char *filename, ios_base::openmode mode = ios_base::in );
void open( const std::string &filename, ios_base::openmode mode = ios_base::in );
第二个只能从C ++ 11开始使用。你显然不是编译在C ++ 11模式或使用过期的编译器。还有另一个重载,需要 const char *
,所以这应该工作不管:
The second one is only available since C++11. You are apparently either not compiling in C++11 mode or using an out of date compiler. There is another overload that takes const char*
, so this should work regardless:
infile.open(fileName.c_str());
这篇关于尝试使用带有infile.open()的字符串变量在c ++中被视为char的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!