目前我使用ifstream读取多个文件,如下所示:
File1:
名称 - 费用
文件2:
名称 - 费用
文件3:
名称 - 费用
我想将所有文件放入一个大文件中并使用ifstream逐行读取。我需要做什么?
这是我的代码:
//Lawn
int lawnLength;
int lawnWidth;
int lawnTime = 20;
float lawnCost;
string lawnName;
ifstream lawn;
lawn.open("lawnprice.txt");
lawn >> lawnName >> lawnCost;
cout << "Length of lawn required: "; // Asks for the length
cin >> lawnLength; // Writes to variable
cout << "Width of lawn required: "; // Asks for the width
cin >> lawnWidth; // Writes to variable
int lawnArea = (lawnLength * lawnWidth); //Calculates the total area
cout << endl << "Area of lawn required is " << lawnArea << " square meters"; //Prints the total area
cout << endl << "This will cost a total of " << (lawnArea * lawnCost) << " pounds"; //Prints the total cost
cout << endl << "This will take a total of " << (lawnArea * lawnTime) << " minutes" << endl << endl; //Prints total time
int totalLawnTime = (lawnArea * lawnTime);
//Concrete Patio
int concreteLength;
int concreteWidth;
int concreteTime = 20;
float concreteCost;
string concreteName;
ifstream concrete;
concrete.open("concreteprice.txt");
concrete >> concreteName >> concreteCost;
cout << "Length of concrete required: "; // Asks for the length
cin >> concreteLength; // Writes to variable
cout << "Width of concrete required: "; // Asks for the width
cin >> concreteWidth; // Writes to variable
int concreteArea = (concreteLength * concreteWidth); //Calculates the total area
cout << endl << "Area of concrete required is " << concreteArea << " square meters"; //Prints the total area
cout << endl << "This will cost a total of " << (concreteArea * concreteCost) << " pounds"; //Prints the total cost
cout << endl << "This will take a total of " << (concreteArea * concreteTime) << " minutes" << endl << endl; //Prints total time
int totalConcreteTime = (concreteArea * concreteTime);
答案 0 :(得分:1)
如果所有内容都在1个文件中,那么您的解决方案将涉及一个循环:
std::string line;
while (std::getline(fin, line))
{
...
}
应该解析每一行以获得您期望的数据:
std::istringstream iss(line);
std::string name;
float cost;
if (!(iss >> name >> cost))
{
// some error occurred, handle it
}
else
{
// do something with the valid data
}