1

我对下面的代码有疑问。在这里,我想编写一个程序,该程序将从文件中获取输入并将其存储在结构向量中,但是当我声明结构类型向量时,它会显示错误。

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

using namespace std;

struct input
{
    char process[10];
    int burst_time;
    int arrival_time;
}input;

int main()
{
    ifstream myfile;
    vector<input> store;// problem with initializing vector

    myfile.open("input.txt",ios::in);

    if(myfile.is_open())
    {
        while(!myfile.eof())
        {
            myfile>>input.process;
            myfile>>input.burst_time;
            myfile>>input.arrival_time;

            store.push_back(input);//showing problem in this line also
        }
    }

    myfile.close();
    return 0;
}
4

2 回答 2

7

您已将名称隐藏inputstruct input. 取消隐藏:

struct intput
{
 // as before
};
于 2013-10-15T12:57:20.693 回答
0

事情就是这样,很简单:

当你声明

struct input
{
    char process[10];
    int burst_time;
    int arrival_time;
} input;

您正在定义一个名为的结构类型input,但也定义了一个名为的变量input,所以主要编译器会感到困惑,它不知道您是指变量还是类型,所以只需重命名结构变量声明并将其称为自己的名称像这样:

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

using namespace std;

struct input // Type defined as "input"
{
    char process[10];
    int burst_time;
    int arrival_time;
} input1; // And variable defined as "input1" consider this to be declared in main, to be a local variable.

int main()
{
    ifstream myfile;
    vector<input> store{};// problem solved referring to type and not variable

    myfile.open("input.txt",ios::in);

    if(myfile.is_open())
    {
        while(!myfile.eof())
        {
            myfile>>input1.process; // Here now the compiler understands that you are referring to the variable and not the type
            myfile>>input1.burst_time;
            myfile>>input1.arrival_time;

            store.push_back(input1);
        }
    }

    myfile.close();
    return 0;
}

这样编译器就不会抱怨了。

还要考虑总是声明一个新类型(如你的结构),第一个字符为大写。Input相反,第一个字符小写input的变量不会混淆并避免这种错误。

于 2017-07-27T05:33:14.803 回答