Parsing through a file

How could I read a file like this:

Category ID Description
1 Pay Check
2 Groceries
3 Utilities
14 Rent
25 Mortgage
6 Travel
7 Refund
8 Restaurant
9 College Fund
10 Transfer From Savings

and place the category id in one variable, and the entire description in another? Preferably, I'd like to have a class whose attributes are categoryID and Description, and set their values according to the file.
One way would be to operator<< in the first number of every line into an int, and then std::getline() the rest of the line. operator<<() is delimited by spaces, but std::getline() can be delimited by whatever you want, default delimiter is newline '\n'.
http://en.cppreference.com/w/cpp/string/basic_string/getline

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>
#include <sstream>

int main() {

    std::stringstream file(
      "1 Pay Check\n"
      "2 Groceries\n"
      "3 Utilities\n"
    );

    while (true)
    {
        int num;
        std::string desc;
        if (file >> num)
        {
            if (std::getline(file, desc))
            {
        	    std::cout << "num = " << num << ", desc = " << desc << std::endl;
            }
            else break;
        }
        else break;
    }

    return 0;
}


Note you'll need to "trim" the leading whitespace in desc.
Last edited on
How would I trim the leading whitespace?
If you know there will always be a space between the number and the start of description, you can just do my_string.erase(0, 1);

Otherwise, you could either call erase repeatedly until the first character isn't whitespace, or you could do something more sophisticated by combining std::erase with std::find_if.

Otherotherwise, shamelessly copy the StackOverflow code :^)
https://stackoverflow.com/questions/1798112/removing-leading-and-trailing-spaces-from-a-string

http://www.cplusplus.com/reference/string/string/erase/
http://www.cplusplus.com/reference/algorithm/find_if/
http://en.cppreference.com/w/cpp/string/byte/isspace
Last edited on
1
2
3
4
5
6
7
8
string trim( string s )          // Remove leading/trailing blanks
{
   unsigned int i = s.find_first_not_of( " " );
   if ( i == string::npos ) return "";

   unsigned int j = s.find_last_not_of( " " );
   return s.substr( i, j - i + 1 );
}

Last edited on
Topic archived. No new replies allowed.