Question

Say I have:

Charlie Smith   134
Alice Jones     245
Bob Richards Hughes 325

in a data file and I want to read them into a map, how would I do this?

This code works fine for just first names, not sure how to extend it to many names...

#include <iostream>
#include <fstream>
#include <string>
#include <map>
#include <iterator>

#define TRUE    1
#define FALSE   0

int main() {
    std::map<std::string, int> contents;
    std::map<std::string, int>::iterator it;

    bool repeat(true);
    std::ifstream infile;
    while (repeat) {
        repeat = false;
        std::cout << "Enter the filename: " << std::endl;
        std::string filename;
        std::getline (std::cin, filename);
        infile.open(filename.c_str());
        if (infile.fail()) {
           std::cerr << "Invalid Filename" << std::endl;
           repeat = true;
        }
    }
    while(!infile.eof()) {
        int a;
        std::string b;
        infile >> b >> a;
        contents[b]=a;
    }
    std::cout << "\n";
    for (it = contents.begin(); it != contents.end(); it++) {
        std::cout << it->first << " " <<  it->second << std::endl;
    }
    return 0;
}
Was it helpful?

Solution

Read a whole line at a time (see e.g. std::getline) then search backwards for the last whitespace (with e.g. std::string::find_last_of). This is the whitespace that will separate the name from the number. Then use std::string::substr to get the name into its own string, and parse the number with e.g. std::stoi.

Note: The string with the full name will have one or more spaces at the end, you would want to remove those before using the string as a key.

OTHER TIPS

You can read line by line from the line and then apply a regular expression to extract the name and the value.

std::string line = "Bob Richards Hughes    325";
std::regex rx("([a-zA-Z\\s]+)\\s+(\\d+)");
std::smatch sm;

if(std::regex_match(line, sm, rx))
{
   std::string name = sm[1];   // Bob Richards Hughes
   std::string value = sm[2];  // 325
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top