c++ - Reading in file with delimiter -


how read in lines file , assign specific segments of line information in structs? , how can stop @ blank line, continue again until end of file reached?

background: building program take input file, read in information, , use double hashing information put in correct index of hashtable.

suppose have struct:

struct data {     string city;     string state;     string zipcode; }; 

but lines in file in following format:

20  85086,phoenix,arizona 56065,minneapolis,minnesota  85281 56065 

sorry still cannot seem figure out. having hard time reading in file. first line size of hash table constructed. next blank line should ignored. next 2 lines information should go struct , hashed hash table. blank line should ignored. , finally, last 2 lines input need matched see if exist in hash table or not. in case, 85281 not found. while 56065 found.

as other 2 answers point out have use std::getline, how it:

if (std::getline(is, zipcode, ',') &&     std::getline(is, city,   ',') &&     std::getline(is, state)) {     d.zipcode = std::stoi(zipcode); } 

the real change made encased extractions within if statement can check if these reads succeeded. moreover, in order done (you wouldn't want type above out every data object), can put inside function.

you can overload >> operator data class so:

std::istream& operator>>(std::istream& is, data& d) {     std::string zipcode;     if (std::getline(is,  zipcode, ',') &&         std::getline(is, d.city,   ',') &&         std::getline(is, d.state))     {         d.zipcode = std::stoi(zipcode);     }      return is; } 

now becomes simple doing:

data d;  if (std::cin >> d) {     std::cout << "yes! worked!"; } 

Comments

Popular posts from this blog

Android layout hidden on keyboard show -

google app engine - 403 Forbidden POST - Flask WTForms -

c - Why would PK11_GenerateRandom() return an error -8023? -