2013-12-20 64 views
0

在我使用ifstream的读取多个文件的那一刻,就像这样:使用Ifstream读取多行?

文件1:

名称 - 费用

文件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); 
+3

隔离你的问题。不要强迫我们读你的整个程序。 – pyon

+3

首先阅读['std :: getline'](http://en.cppreference.com/w/cpp/string/basic_string/getline),可能还有['std :: istringstream'](http:// en.cppreference.com/w/cpp/io/basic_istringstream)进一步解析。 –

回答

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 
}