Reading in a delimited file

How to read lines from a file and assign specific segments of this line for information in structures? And how can I stop on an empty line and then continue until the end of the file is reached?

Reference Information. I am creating a program that will accept an input file, read information and use double hashing so that this information is placed in the correct hash table index.

Suppose I have a structure:

struct Data
{
    string city;
    string state;
    string zipCode;
};

But the lines in the file are in the following format:

20

85086,Phoenix,Arizona
56065,Minneapolis,Minnesota

85281
56065

, . . - , , -. . - , -. . , , , , , - . , 85281 . 56065.

+4
3

, std::getline, :

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

, , , if, , . , , ( Data), .

>> Data :

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;
}

, :

Data d;

if (std::cin >> d)
{
    std::cout << "Yes! It worked!";
}
+4

getline <string> :

string str;                      // This will store your tokens
ifstream file("data.txt");

while (getline(file, str, ',')   // You can have a different delimiter
{
     // Process your data

}

stringstream:

stringstream ss(line);           // Line is from your input data file
while (ss >> str)                // str is to store your token
{
     // Process your data here
}

. , .

+2

, , std::getline

std::string s;
std::getline( YourFileStream, s, ',' );

int, std::stoi

, std:: istringstream std:: getline.

Data d = {};

std::string line;

std::getline( YourFileStream, line );

std::istringstream is( line );

std::string zipCode;

std::getline( is, zipCode, ',' );

d.zipCode = std::stoi( zipCode );

std::getline( is, d.city, ',' );
std::getline( is, d.state, ',' );
0
source

Source: https://habr.com/ru/post/1530897/


All Articles