【问题标题】:I need to pass an ifstream into a function so i can add it to a vector我需要将一个 ifstream 传递给一个函数,这样我就可以将它添加到一个向量中
【发布时间】:2012-04-09 07:04:19
【问题描述】:

我是编程新手,需要一些帮助,谢谢!

我有一个名为 namelist.txt 的文本文件。我需要将 inFile 传递给一个函数,该函数可以将名称列表(以 firstname lastname 的格式,例如:chuck norris)添加到一个名为 vecStudent 的向量中。你如何将 inFile 传递给函数,如果可能的话,我将如何将名称添加到向量中?

#include <iostream>
#include <fstream>
#include <string>
#include <vector>

using namespace std;

ifstream readtoVec(); //function prototypes
int displayAll();
int add();
int remove();
int savequit();

int main()
{
char cInput;
string strFileName;
vector<string> vecStudent;
ifstream inFile;
ofstream outFile;

{
    cout << "Please Enter the data file name (with location): ";
    cin >> strFileName;

    inFile.open(strFileName.c_str());

    if (inFile.fail())

    {
        cout << "Input file error!" << endl;

        return -1;
    }

    // call a function to read the contents of the input file into vecStudent
    else
    {
        readtoVec (ifstream& inFile);

我在这里遇到一个错误,称为“不允许使用类型名称”

}



while (true)
{
    cout << "--------------------------------------" << endl;
    cout << " Student Record - Main Menu " << endl;
    cout << "--------------------------------------" << endl;
    cout << " Enter 1 to display ALL students " << endl;
    cout << " Enter 2 to add a student name " << endl;
    cout << " Enter 3 to delete a student name " << endl;
    cout << " Enter 4 to SAVE and quit the program " << endl;
    cout << "--------------------------------------" << endl;
    cout << " Enter menu option: " ;
    cin >> cInput;
    switch (cInput)
    {
        case '1':
            //call function
            break;
        case '2':
            //call function
            break;
        case '3':
            //call function
            break;
        case '4':
            //call function
            return 0;
        default:
            cout << "invalid input" << endl;
            break;
    }

return 0;
}

【问题讨论】:

    标签: function visual-c++ vector ifstream


    【解决方案1】:

    ifstream readtoVec(); //函数原型

    这表示readtoVec() 返回一个ifstream,但这里不接受任何参数:

    readtoVec(ifstream&inFile);

    当您调用readtoVec 时,您(有点)试图传递一个参数。至少根据您尝试调用它的方式,声明应该类似于void readtoVec(ifstream &amp;);

    当你调用它时,你确实指定参数的类型,所以调用看起来像:readtoVec(inFile);

    【讨论】:

    • 感谢您的回复,然后我将如何将 .txt 文件中的名称列表添加到函数 readtoVec 中的向量中?我认为 void 不会将任何内容返回给当时的 main。
    猜你喜欢
    • 1970-01-01
    • 2015-12-14
    • 1970-01-01
    • 1970-01-01
    • 2016-09-01
    • 2016-11-26
    • 2023-04-04
    • 2021-02-04
    • 1970-01-01
    相关资源
    最近更新 更多