1

I am in the middle of a college project which kind of looks like a students' database. Each line of the text file follows this "model":

 age ; full_name ; avg

I need to read the text file and store everything in a vector of structs and I could do that if the name was only one word. Well, obviously, age is an int, avg is a double, but what about the full name? I can't just use file >> full_name;, with full_name being a string because it would stop reading to it once it gets to a whitespace. The getline() function would store everything in one place so I am not sure what to do.

Please share your knowlegde with this young mind x)

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
Daniel Marques
  • 506
  • 5
  • 20
  • [Heavily related](http://stackoverflow.com/questions/23047052/why-does-reading-a-record-struct-fields-from-stdistream-fail-and-how-can-i-fi). – πάντα ῥεῖ Mar 23 '16 at 18:04
  • 1
    `std::getline` can use a custom delimiter, those `;` look like they might come in handy :) – melak47 Mar 23 '16 at 18:09
  • Very similar problem indeed. But I didn't understand what the solution was. I don't want to use more than one string for the name becase it can has a variable amount of words. Also, rearranging the file is not an option. – Daniel Marques Mar 23 '16 at 18:10
  • @melak47 Thanks! I just checked the full syntax for it and I'll give it a try with the delimiter. – Daniel Marques Mar 23 '16 at 18:15
  • @DanielMarques _"Very similar problem indeed. But I didn't understand what the solution was."_ There wasn't/isn't _the solution_, but [my answer for using delimited input](http://stackoverflow.com/a/23070803/1413395) goes best in the direction you need. – πάντα ῥεῖ Mar 23 '16 at 18:23
  • Possible duplicate of [How can I read and parse CSV files in C++?](http://stackoverflow.com/questions/1120140/how-can-i-read-and-parse-csv-files-in-c?s=1|3.1427) – πάντα ῥεῖ Mar 23 '16 at 18:25
  • @melak47 I tried getline() with the delimiter but it didn't work. I'm sorry, I'm new, but can any of you please explain how can I do this with them? – Daniel Marques Mar 23 '16 at 19:27

1 Answers1

1

As many others pointed out, you can use std::getline to read chars till a delimiter.

Consider this snippet of code as a starting point:

int age;
std::string name;
double average;

// ... Open the file which stores the data ... 

// then read every line. The loop stops if some of the reading operations fails
while ( input >> age  && 
        std::getline(input, name, ';')  &&        // consume the first ;
        std::getline(input, name, ';')  &&        // read the name
        input >> average ) {
    // do whatever you need with the data read
    cout << "age: " << age << " name: " << name << " average: " << average << '\n';
}
Bob__
  • 12,361
  • 3
  • 28
  • 42