gpt4 book ai didi

c++ - 使用 Ifstream 读取多行?

转载 作者:行者123 更新时间:2023-11-28 07:12:53 25 4
gpt4 key购买 nike

目前我正在使用 ifstream 读取多个文件,如下所示:

文件 1:

name - cost

文件2:

name - cost

文件 3:

name - cost

我想将所有文件放入一个大文件中,然后使用 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);

最佳答案

如果所有内容都在 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
}

关于c++ - 使用 Ifstream 读取多行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20707257/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com