c++ - 在 C++ 中通过引用流和字符调用

标签 c++

我最近的家庭作业是编写一个读取文本文件并输出行数、单词数和字符数的程序。

我才刚开始,我现在要做的就是让用户输入文件名,然后文件就会打开。这是我的无效代码,我一定遗漏了一些明显的东西,我只是想将流和字符传递给“输入”函数。

有什么建议吗?

#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/

相关文章:

c++ - 如何从 XML 文件中读取信息 C++

c++ - 如何检查派生类中对象的类型名称?

c++ - libqmi应该如何链接?

c++ - 如何运行一段代码,使其不会在 QtQuick 中窃取所有焦点?

c++ - 从 wchar_t 转换为 char,反之亦然

java - InetAddress.getByName 失败 getaddrinfo 工作

c++ - 为什么这个函数返回的值与我在内联时返回的值不同?

c++ - 将字符串相关函数从 C++ 转换为 C

c++ - 在位域 [dcl.enum] [class.bit] 中保存枚举类型

c++ - CFileDialog (MFC) 异常