如何从整个代码的函数中打开文件
How do I open a file from a function for the whole code?
我正在研究一个简单的 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);
}
}
#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();
}
你的代码有很多缺陷,
-
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());
相关文章:
- 用C++在单独的头文件中完成函数体
- C++-试图将函数指针推回到另一个CPP文件中的矢量时出错
- 输入到文件并输出到另一个文件,并将流文件传递给函数
- 头文件、宏和内联函数c++
- 如何使用单独文件中的派生类访问友元函数对象
- C++无法定义虚拟函数 OUTER 类和头文件
- 回溯C++不打印函数,因此文件
- 如何从另一个文件继承私有成员变量和公共函数
- 从函数角度看ID到文件路径的内部与外部映射
- 区分非成员函数和头文件中的成员函数
- 如何使用对C函数和类对象的外部调用来处理C++头文件
- 如何在其他文件中使用函数
- 整数键映射到头文件中的成员函数指针
- C++(.cpp文件和.h文件)拆分代码并添加一个函数,提取 - 这很容易吗?
- 给定一个C++嵌套的私有结构类型,是否有从文件范围静态函数访问它的策略
- 用"=default"声明的函数应该只在头文件中执行
- 将单独的头文件和类定义文件链接到主函数文件 - G++ 返回重载"undefined reference to"构造函数
- C++ - 在一个函数/文件中初始化变量然后在main()/另一个文件中使用它的最佳方法是什么?
- C++单独的函数文件
- 只对单个函数/文件启用编译器优化