0

So I have a project (I don't expect anyone to do my hw for me but I'm getting boned right now on the first of 3 data structures just so I can start my project) where I need to fill a couple maps by running through some files, my example file is set up simply where I need to extract a long as the key for a value that will be a string in the map, like so:

0 A

1 B

2 C

Where my pairs would obviously be 0 is the key to A which would be a string for this project, the issue is that my instructor also said this would be a possible format:

0 W e b 1

1 W e b 2

2 W e b 3

where 0 is the key to "W e b 1". I know that I need to divide on white space but honestly I have no clue even where to begin, I have tried a couple methods but I can only get the first character of the string in this second case.

Here is ultimately what I am sitting on, don't worry about the whole boolean return and the fact that I know the whole opening the file and checking of it should occur outside this function but my professor wants all that in this function.

bool read_index(map<long, string> &index_map, string file_name)
{
    //create a file stream for the file to be read
    ifstream index_file(file_name);

    //if file doesn't open then return false
    if(!index_file)
        return false;

    string line;
    long n;
    string token;
    //read file
    while(!index_file.eof())
    {
        getline(?)
        //not sure how to handle the return from getline
    }

    //file read?
    return !index_file.fail();
}
WhozCraig
  • 65,258
  • 11
  • 75
  • 141
Pacman2194
  • 3
  • 1
  • 3
  • 1
    Right off the bat, [`while(!index_file.eof())` is wrong](http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong). Use `while(std::getline(index_file, line))` and lose the `getline` in the loop body. *Always* check your IO operations for success; never assume they didn't fail. – WhozCraig Oct 17 '14 at 21:40

1 Answers1

0

You could possibly use strtok() function for line splitting if you are a pure C lover, but there's a good old C++ way for splitting file data: just redirect cin stream to your file, it splits any valid separators -- whitespaces, tabs, newlines, you'll need only to keep a line counter for yourself

std::ifstream in(file_name);
std::streambuf *cinbuf = std::cin.rdbuf(); //better save old buf, if needed later
std::cin.rdbuf(in.rdbuf()); //redirect std::cin to file_name

// <something>

std::string line;
while(std::getline(std::cin, line))  //now the input is from the file
{
    // do whatever you need with line here, 
    // just find a way to distinguish key from value
    // or some other logic
}
MasterAler
  • 1,614
  • 3
  • 23
  • 35