我有一個文本文件,我從中輸入數據,但我似乎無法得到它的權利。C++,使用獲取和>>爲ifstream
下面是從文本文件作爲示例兩行(這些都不是真正的人也不用擔心):
Michael Davidson 153 Summer Avenue Evanston CO 80303
Ingrid Johnson 2075 Woodland Road Aurora IL 60507
這裏是代碼,我必須加載文本文件,並把數據到一個結構。我對C++還很陌生(很明顯),我很難一起使用get和>>。我有下面的代碼,工作正常,直到我到達「狀態」,然後出現問題。謝謝您的幫助!
//constants
const int FIRST_NAME_LEN = 11;
const int LAST_NAME_LEN = 13;
const int ADDRESS = 25;
const int CITY_NAME_LEN = 16;
const int STATE_LEN = 3;
//define struct data types
struct CustomerType {
char firstName[FIRST_NAME_LEN];
char lastName[LAST_NAME_LEN];
char streetAddress[ADDRESS];
char city[CITY_NAME_LEN];
char state[STATE_LEN];
int zipCode;
};
//prototype function
ifstream& getInfo(CustomerType& CT_Struct, ifstream& infile);
int main() {
//declare struct objects
CustomerType CT_Struct;
ifstream infile("PGM951_customers.txt");
if(!infile) {
cerr << "Could not open the input file." << endl;
exit(1); //terminates the program
}
//call the function
getInfo(CT_Struct, infile);
return 0;
}
ifstream& getInfo(CustomerType& CT_Struct, ifstream& infile) {
while(infile) {
infile.get(CT_Struct.firstName, sizeof(CT_Struct.firstName));
infile.get(CT_Struct.lastName, sizeof(CT_Struct.lastName));
infile.get(CT_Struct.streetAddress, sizeof(CT_Struct.streetAddress));
infile.get(CT_Struct.city, sizeof(CT_Struct.city));
infile.get(CT_Struct.state, sizeof(CT_Struct.state));
infile >> ws;
infile >> CT_Struct.zipCode;
cout << CT_Struct.firstName << " | " << CT_Struct.lastName << " | " << CT_Struct.streetAddress
<< " | " << CT_Struct.city << " | " << CT_Struct.state << " | " << CT_Struct.zipCode << endl;
}
return infile;
}
===編輯=========== 閱讀的狀態在8字符只有我亂搞,然後我忘了改回來...對不起。
「這些不是真正的人不擔心」 這些傢伙乞討不同:http://en.wikipedia.org/wiki/Michael_Davidson;) – 2009-05-06 19:59:19
但他的意見並不重要,因爲他不是真的。 ;) – jalf 2009-05-06 20:00:50
你不要告訴我們「出了什麼問題」!狀態是否存在,但是zip文件崩潰了,或者狀態是錯誤的? – crashmstr 2009-05-06 20:13:36