我正在研究一个简单的c ++脚本,并希望在函数内部打开一个文件的整个过程。但是,当我尝试时,我的主要功能出错了。谁能帮我?这是我的代码:
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
using namespace std;
string openFile(string fileName);
int main(void)
{
string fileName;
cout << "Please input the file name (including the extension) for this code to read from." << endl;
cin >> fileName;
openFile(fileName);
fout << "File has been opened" << endl;
return 0;
}
string openFile(string fileName)
{
ifstream fin(fileName);
if (fin.good())
{
ofstream fout("Output");
cout << fixed << setprecision(1);
fout << fixed << setprecision(1);
//Set the output to console and file to be to two decimal places and
//not in scientific notation
}
else
{
exit(0);
}
}
答案 0 :(得分:1)
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
using namespace std;
ofstream fout;
string openFile(string fileName);
void closeFile();
int main(void)
{
string fileName;
cout << "Please input the file name (including the extension) for this code to read from." << endl;
cin >> fileName;
openFile(fileName);
if (fout.good()) //use fout in any way in this file by cheking .good()
cout << "File has been opened" << endl;
closeFile();
return 0;
}
string openFile(string fileName)
{
cout << fixed << setprecision(1);
fout.open(fileName.c_str());
if (fout.good()) {
fout << fixed << setprecision(1);
cout<<"Output file opened";
}
}
void closeFile()
{
fout.close();
}
答案 1 :(得分:0)
你的代码有很多缺陷,
fout << "File has been opened" << endl;
,应该是,
cout << "File has been opened" << endl;
你不能再次重新定义相同的变量。
ofstream fout("Output");// first
cout << fixed << setprecision(1);
fout << fixed << setprecision(1);
//Set the output to console and file to be to two decimal places and
//not in scientific notation
ofstream fout("Tax Output.txt");//second
在最后一行给变量添加一些其他名称。
std::string
,您应该通过const char *
, ifstream fin(fileName)
;
应该是,
ifstream fin(fileName.c_str());