读取文件内容的C++程序,高手帮忙看看

来源:百度知道 编辑:UC知道 时间:2024/05/16 17:14:31
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s,line;
cout << "input the filename:";
cin >> s;

if (!infile) ifstream infile(s.c_str());
{
cerr << "error:unable to open input file: "<< endl;
return -1;
}
while (getline(infile, line))
cout << line << endl;
system("pause");
return 0;
}
上面粘贴错了:
应该是:
ifstream infile(s.c_str());
if(!infile)
{//下面都相同了
}

有什么问题啊?

#include <iostream>
#include<fstream>//文件流头文件,没有编译不通过
#include <string>
using namespace std;
int main()
{
string s,line;
cout << "input the filename:";
cin >> s;

ifstream infile(s.c_str());
if (!infile)
{
cerr << "error:unable to open input file: "<< endl;
return -1;
}
while (getline(infile, line))
cout << line << endl;
system("pause");
return 0;
}

输入文件路径时注意‘\’为转义字符,要用‘\\’输入。如D:\text.txt要写成D:\\text.txt