我最近的家庭作业是编写一个读取文本文件并输出行数、单词数和字符数的程序。
我才刚开始,我现在要做的就是让用户输入文件名,然后文件就会打开。这是我的无效代码,我一定遗漏了一些明显的东西,我只是想将流和字符传递给“输入”函数。
有什么建议吗?
#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;
//Define functions.
void input(ifstream& fin, char& fileName);
int main()
{
ifstream fin;
char fileName[20];
input(fin, fileName);
return 0;
}
void input(ifstream& fin, char& fileName)
{
cout << "Input file name: ";
cin >> fileName;
fin.open(fileName);
if(fin.fail())
{
cout << "The file: " << fileName << " does not open." << endl;
exit(1);
}
//return;
}
最佳答案
这可能会让你更接近。至少过去了你的编译错误,但你仍然需要做一些事情。获取引用手册和调试器。
#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;
//Define functions.
void input(ifstream& fin, string& fileName);
int main()
{
ifstream fin;
string fileName;
input(fin, fileName);
return 0;
}
void input(ifstream& fin, string& fileName)
{
cout << "Input file name: ";
cin >> fileName;
fin.open(fileName.c_str());
if(fin.fail())
{
cout << "The file: " << fileName << " does not open." << endl;
exit(1);
}
//return;
}
不是我这样做的方式,但你总得找个时间学习。祝你好运!
关于c++ - 在 C++ 中通过引用流和字符调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12655726/