[英]how to read line by line in a text file and populate a pointer to object array
使用該線程的解決方案,我對如何在文本文件中逐行讀取有一個大致的想法。 我的問題出現在如何將數據填充到我的電話簿中,這是一個指向對象數組的指針。
這是我的文本文件輸出的內容。
Albert, Fred
4541231234
8888 Avenue Drive
Doe, John
6191231234
1234 State Street
Smith, Mike
8791231234
0987 Drive Avenue
我想要做的是解析每一行並使用填充我的電話簿所需的任何信息,定義為。
class AddressBook
{
private:
Contact* phoneBook[maxSize]; //array of contact pointers
...etc
}
class Contact
{
public:
Contact();
std::string firstName;
std::string lastName;
std::string name; //lName + fName
std::string phoneNumber;
std::string address;
};
我可以讓它逐行閱讀,至少我認為,但我不知道從哪里開始如何讓它識別出它是名字,姓氏,電話號碼或地址,因為它們是所有字符串。
void AddressBook::writeToFile(Contact * phoneBook[])
{
std::string line;
std::ifstream myFile("fileName.txt");
if (myFile.is_open())
{
while (getline(myFile, line))
{
//do something
}
myFile.close();
}
}
您必須以四行為一組讀取文件的內容。
std::string line1; // Expected to be empty
std::string line2; // Expected to contain the name
std::string line3; // Expected to contain the phone number
std::string line4; // Expected to contain the address.
而且,而不是while(getline(...))
語句,使用:
while (true)
{
if ( !getline(myFile, line1) )
{
break;
}
if ( !getline(myFile, line2) )
{
break;
}
if ( !getline(myFile, line3) )
{
break;
}
if ( !getline(myFile, line4) )
{
break;
}
// Now process the contents of lines
}
您可以通過為行組使用數組來簡化一點
std::string lines[4];
while ( true )
{
// Read the group of lines
for (int i = 0; i < 4; ++i )
{
if ( !getline(myFile, lines[i]) )
{
break;
}
}
// Process the lines
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.