最好使用getline或cin从输入文件填充数组?

时间:2014-03-24 02:25:15

标签: c++ fstream

我的问题可能在于索引或我的语法。我正在尝试填充两个 输入文件中的数组names[]shares[]

程序的一半,手动输入,工作正常。每次尝试fstream的一半 已打印一个空的输出表,其中-1.#IND为每个的百分比 股东。

我尝试了cin >> name >> sharegetline(shareFile, name)while(shareFile >> name >> share){ ... names[i] = name; shares[i] = share;,但是 我不知道如何以正确的方式使用getline我认为所以我正在使用第一个。就像我说的那样,
我不知道我的索引或代码是否有问题。

这是(我相信)问题的功能,但也许它不是以正确的方式传递事物。

void getFileInputs(string names[], int shares[], int size)
{
    string file;
    string name;
    int share = 0;
    bool isOpen = true;
    ifstream shareFile("inputfile.txt");

    cout << "*----------------------------------*\n"
        << "*     Input From File:             *\n"
        << "*----------------------------------*\n";
    cout << "Please enter the name of the file (.txt): ";
    cin >> file;
    cout << "\n";

    shareFile.open("inputfile.txt");

    if(file == "inputfile.txt" || file == "inputfile")
    {
        int i = 0;
        do{

        for(i = 0; i < size; i++)
            {
                shareFile >> names[i] >> shares[i];
            }

        if(shareFile.eof())
        {
            isOpen = false;
        }
    }while(isOpen == true && shareFile >> name >> share);
    }
    else
    {
        cout << "Unrecognized file name. \n" << endl;
        isOpen = false;
    }
}

1 个答案:

答案 0 :(得分:1)

当前的问题是以下代码行:

shareFile.open("inputfile.txt");

上面几行,当您构造shareFile对象时,您使用文件名打开它但没有关闭它。在已打开的文件流上调用open()会在文件流的错误掩码中设置错误。因此,任何执行输入的尝试都将失败,直到从流中清除错误。

此外,由于file是文件的名称,我假设您打算用它打开它。如果是这样,以上内容应改为:

std::ifstream shareFile; // default-construct; no file is opened yet
// ...
shareFile.open(file.c_str()); // open it with the value of user-input

另一个问题是循环以及如何将文件中的值分配给数组。首先,您不应该使用do {} while()而是使用for()循环。此外,如果shareFile命中流的末尾,则循环将终止;因此没有理由使用布尔isOpen变量:

for (int i = 0; shareFile >> name >> share; ++i)
{
    // ...
}

现在,一旦成功地将值放入nameshare,您就可以将它们分配给数组中的值:

for (int i = 0; shareFile >> name >> share; ++i)
{
    names[i] = name; shares[i] = share;
}