![](/img/trans.png)
[英]Reading from a CSV file using CPP, compiling the code with a CMake file
[英]Reading from a file,using headers and cpp's
好的,所以我有一个3级的车辆继承树。 叶子类(树上最后的叶子类)为六个。 我想创建一个将从.txt文件读取的函数,然后将信息分配给不同的变量(例如,该文件将包含2006 Toyota Supra Diesel并将其分配给year
, brand
, model
, fuel_type
)。 实际上,我确实做到了这一点,但是之后,当我将代码拆分为.h和.cpp文件时,该函数就停止了工作。
void Cars::txt_input()
{
getline(file,input); //This is in the .cpp file for one of the
year = atoi(input.c_str()); //child classes.
getline(file,input);
brand = input;
getline(file,input);
model = input;
getline(file,input);
passenger_capacity = atoi(input.c_str());
getline(file,input);
engine_power = atoi(input.c_str());
getline(file,input);
max_speed = atoi(input.c_str());
getline(file,input);
fuel_type = input;
getline(file,input);
wheel_drive = input;
getline(file,input);
average_cons = atoi(input.c_str());
getline(file,input);
number_doors = atoi(input.c_str());
getline(file,input);
cType = input;
getline(file,input);
price = atoi(input.c_str());
}
在我的main()中,我声明了ifstream file("vehicles.txt")
和string input
,它们在拆分代码之前运行良好。 另外,我已经将ifstream file
和string input
变量创建为基类的受保护成员,否则它将无法编译,因为它找不到任何要使用的文件和输入变量。 但是,现在函数似乎根本不从main()
中获取变量,而只是用0或N / A填充所有对象的字段(根据构造函数)。
for (int i = 0; i < 11; i++)
{
if(i<4)
vehicles.push_back(new Cars());
vehicles[vehicles.size()-1]->txt_input();
}
if(i==4 || i==5)
{
vehicles.push_back(new Bus());
vehicles[vehicles.size()-1]->txt_input();
}
//...
}
这就是我在main()
创建对象的方式。 如我所说,当我在Main.cpp中拥有所有代码时,它可以完美运行。 另外,我尝试将(ifstream file,string input)
作为参数传递给txt_input()
函数,但它会产生错误C2248。 这是我的第一篇帖子,抱歉,如果有任何歧义。 如果需要,我将提供更多代码/信息。
class Vehicles
{
public:
Vehicles();
virtual void txt_input();
virtual void user_input();
virtual void output();
void red_output();
int getPC();
int getPrice();
string getBrand();
void open_file();
protected:
string brand, model, type;
int year, passenger_capacity, price;
double engine_power, max_speed;
ifstream file;
string input;
};
这是父类。
您已经在main
设置了变量file
,但使用的成员变量也被命名为file
,但未设置为vehicles.txt
。 一种方法是使构造函数将文件名作为参数。
EG代码-未编译的构造函数
Cars::Cars(const ifstream& if) : file(if) { }
当将其添加到vector vehicles.push_back(new Cars(file)); // this is the file defined in main set to "vehicles.txt"
vehicles.push_back(new Cars(file)); // this is the file defined in main set to "vehicles.txt"
注意:在命名类成员变量(例如mFile,m_file,_file)时,请使用约定,以避免混淆。
因此,根据评论,问题在于您的变量file
现在是Vehicles
的成员,与您的主file
中的先前ifstream无关...
因此,以下内容可能会有所帮助:
/*virtual*/ void Vehicles::txt_input(std::istream& file)
{
std::string input;
getline(file, input);
year = atoi(input.c_str());
getline(file, input);
brand = input;
// And so on...
}
因此,您的循环变为:
std::ifstream file("vehicles.txt");
for (int i = 0; i != 4; i++) {
Cars* cars = new Cars();
cars->txt_input(file);
vehicles.push_back(cars);
}
for (int i = 0; i != 2; i++) {
Bus* bus = new Bus();
bus->txt_input(file);
vehicles.push_back(bus);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.