-1

Suppose there is a text file containing these in the fallowing style:

      name: natalie, sarah
      surname: parker
      age: 24
      contry: dubai

I want to get natalie and sarah as the name, parker as the surname and so on. After this, somewhere in my code I need variables name, surname, age (as natalie, sarah, parker, 24 etc..).

I think, first I need to read file and store it in an array and than parse it with using delimiters which are : " "(space) or ":" in order to parse <surname: parker> this one, and also use "," comma as a delimiter in order to parse <natalie, sarah>.

I could store the text in an array or use getline(textfile, size) for getting the lines, because I need exactly one line in each time. Which is the most suitable do you think? And how we can do the parsing?

Niels
  • 48,601
  • 4
  • 62
  • 81

3 Answers3

1

You are very close to the target. I just have a little bit suggestions:

  • Use std::map to store data from file
  • Use while loop to get each line from file, use split or boost::split the string by : to get key and value and store them in map.
Community
  • 1
  • 1
billz
  • 44,644
  • 9
  • 83
  • 100
  • Just to add, I'd also look into tokenizing: it'll come in handy for things like "name: natalie, sarah, ..., ...,". – paul23 Jan 27 '13 at 12:02
1

Use regular expression to solver it easier. Pattern like this : "name:([\w,]+)surname(\w+)"

Deeroad
  • 11
  • 1
0

I could think of something like this (simplified; no error checking or optimization and such; this is untested, but should work):

std::ifstream file(myfile);
std::string line;

std::map<const std::string, std::string> dataset;

while (file >> line) {
    size_t var_start = line.find_first_not_of(" \t"); // get beginning of the variable name
    size_t var_end = line.find_first_of(":"); // get the end of the variable name
    if (var_start == std::string::npos || var_end == std::string::npos) // any not found?
        continue; // skip this line
    std::string var_name = line.substr(var_start, var_end - var_start); // get the variable name
    std::string var_value = line.substr(var_end + 1); // get the variable content

    // now do something, e.g. safe it
    dataset[var_name] = var_value;
}
Mario
  • 35,726
  • 5
  • 62
  • 78
  • when I need to use dataset[var_name] how do I call it? – gozde umay Jan 27 '13 at 15:03
  • like dataset[0] or dataset[name]? – gozde umay Jan 27 '13 at 15:03
  • It's a map, the key is a `std::string`, so you'd use `dataset["name"]` for example, but that's really up to you (you could just compare `var_name` to literals and assign different variables). – Mario Jan 27 '13 at 16:03
  • how can I handle the "," part? name: natalia, sarah and I should get natalia and sarah seperately, how can I do that? – gozde umay Jan 28 '13 at 13:50
  • The same way, look for the position of the separator (e.g. using `find_first_of()`), then split it as I did above (e.g. using `substr()`). – Mario Jan 28 '13 at 18:59