这是打开任何文本文件的正确方法吗?这是我正在使用的代码的一小部分。尝试通过putty打开文件时,我不断收到错误消息。
int main(int argc, char *argv[])
{
string a;
a = argv[1];
//a = a + ".txt";
ifstream fin;
fin.open(a);
}
x.cpp:在函数'int main(int,char **)'中:
x.cpp:1225:12:错误:没有匹配函数来调用'std :: basic_ifstream :: open(std :: string&)'
fin.open(a)的
x.cpp:1225:12:注意:候选人是: 在x.cpp:7:0中包含的文件中: /usr/include/c++/4.8.2/fstream:538:7:注意: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]
open(const char * __s,ios_base :: openmode __mode = ios_base :: in)
/ usr / include / c ++ / 4.8.2 / fstream:538:7:注意:参数1从'std :: string {aka std :: basic_string}'到'const char *'没有已知的转换“
非常感谢任何帮助。
答案 0 :(得分:2)
您可以将程序参数直接传递给fin.open
,您无需先转换为string
:
#include <iostream>
#include <fstream>
using namespace std;
int main(int argc, char *argv[])
{
ifstream fin;
fin.open(argv[1]);
string line;
if (fin.is_open()) {
getline(fin, line);
cout << line << '\n';
}
fin.close();
}