Reputation: 355
I have a quite simple situation I don't know how to resolve :
I am parsing a file with addresses (city, street and street number), and have the following class :
class Address
{
std::string city;
std::string street;
std::string number;
};
I would like to create an object for each address I find in the file, but I can't know how many there are since the file can change. Is there a way to create an Array of objects ; or any more suitable solution ?
NOTE : Parser works fine, all there is to do is to set the values in the objects.
Upvotes: 1
Views: 179
Reputation: 264421
Like @Serge but rather than use the parser directly define an input operator.
struct Address
{
std::string city;
std::string street;
std::string number;
friend std::istream& operator>>(std::istream& in, Address& address) {
return parseAddress(in, address);
}
};
std::istream& parseAddress(std::istream& in, Address& address)
{
//TODO: implement
//TODO: return stream.
// If the parse failed.
// Then set the bad bit on the stream.
}
int main()
{
std::ifstream file("address.txt");
std::vector<Address> addresses(std::istream_iterator<Address>(file),
std::istream_iterator<Address>());
}
Upvotes: 1
Reputation: 15040
You can use std::vector for such purpose: http://en.cppreference.com/w/cpp/container/vector
#include <vector>
struct Address
{
std::string city;
std::string street;
std::string number;
};
bool parseAddress(Address& address)
{
//TODO: implement
//TODO: return "true" if another address has been successfully parsed
}
int main()
{
std::vector<Address> addresses;
Address current;
while(parseAddress(current))
{
addresses.push_back(current);
}
return 0;
}
Upvotes: 4