Shawn
Shawn

Reputation: 25

Parsing comma seperated data of varying types in c++

I am writing in C++.

I have a comma delimited data file that I need to parse. There are four elements (so 3 commas) in each row and fixed number of rows (around 200). The problem I have been running into is that the first two elements are string data types, the third element is an integer data type, and the last element is of the double type. An example of the data is below:

John Smith, PG, 10400, 41.4554
Jane Doe, PG, 4500, 32.4543
Charles Johnson, SG, 8800, 23.2323
Rick Grimes, C, 10500, 40.4550
.....

Types: String, String, Int, Double

I have an array for each of these elements that I would like to populate. Sample code would be much appreciated!

Thank you so much.

Upvotes: 1

Views: 129

Answers (2)

Faisal
Faisal

Reputation: 361

Use ifstream::getline in conjunction with sscanf.

#include <fstream>
#include <iostream>

int main()
{
  std::ifstream file;
  file.open("Data.txt");
   char line[100];
   char elem1[10], elem2[10];
   int elem3;
   double elem4;
   int linenum = 0;
  while (!file.eof()) {
    linenum++;
    file.getline(line, 100);
    sscanf(line, "%s,%s,%d,%f\n", elem1, elem2, elem3, elem4);
    // Use elem1, elem2, elem3 and elem4 the way you want to. 

  }
  return 0;
}

Upvotes: 0

villasv
villasv

Reputation: 6841

When reading structured data sometimes is good to use the good ol' scanf.

Something along these lines would do the job:

char n[20], p[5];
int i;
double d;

scanf("%[^,], %[^,], %d, %lf\n", n, p, &i, &d);

Here n and p are C strings, which you can convert to std::string if desired.

Adding some explanation on what the heck is that scanf string??

  • [^,] is an specifier much like regular expressions that says: keep reading until you find a ,.
  • When you put extra stuff like the , between the variables scanf` won't capture them, just match and keep going
  • Why that \n at the end? To match the line-feed and prevent it from being processed by the next scan, which would make it enter the name variable.

scanf is really powerful for structured data. More in-depth refs.

You could also do this with regexp, and then convert the string tokens to integer and double respectively.

Upvotes: 1

Related Questions