Delimited Text File

Hello everyone I'm new to this site and to C++, but I do have some programming experience in C#. I've spent the last two or three days learning Java and C++ and I was wondering if any could help me with taking a text file and sorting it.

This is the text file: Format is Title, Genre, Mins, Year, Cost

datafile.txt

Amadeus,Drama,160 Mins.,1984,14.83
As Good As It Gets,Drama,139 Mins.,1998,11.3
Batman,Action,126 Mins.,1989,10.15
Billy Elliot,Drama,111 Mins.,2001,10.23
Blade Runner,Science Fiction,117 Mins.,1982,11.98
Shadowlands,Drama,133 Mins.,1993,9.89
Shrek,Animation,93 Mins,2001,15.99
Snatch,Action,103 Mins,2001,20.67
The Lord of the Rings,Fantasy,178 Mins,2001,25.87

Could someone help me sort the txt file by Title, Year, and Genre? So far I learned how to Open the file with getline but that's it.
Thanks!
Last edited on
I would use the getline to read each line and three STL maps to hold the line and use Title, Year and Genre as the key for each of the three maps. Then you can iterate thru the map to get them sorted.
Last edited on
Thanks Im going to look into that right now.
You could start with
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
29
30
31
32
33
34
35
36
37
38

#include <iostream>
#include <fstream>
#include <cerrno>
#include <string>
#include <sstream>

using std::string;
using std::cout;
using std::endl;
using std::ifstream;
using std::istringstream;

int main(int argc, char **argv)
{
  ifstream inStrm("datafile.txt");
  int      lineNum(0);
  if ( inStrm.is_open() ) {
      string str,token;
      while(getline ( inStrm, str) ) {
          istringstream iss(str);
          // Some debug
          cout << "LineNum(" << lineNum << "): ";
          while (getline(iss, token,',') ) {
             // More debug
             cout << token << " ";
          }
          // More debug
          cout << endl;
          lineNum++;
      }
      inStrm.close();
  }
  else {
     cout << "Error: Unable to open: " << strerror(errno) << endl;
  }
  return 0;
}
@histrungalot thank you i understand whats going on. That was a big help and im adding this to my notes.
Happy to help
Topic archived. No new replies allowed.