2013-12-20 61 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 
}