parsing a string and stroing in struct

Hello everyone

Could any one please help me parsing a line having different fields separated through commas. I want to store each comma separated sub string in a struct member variable. The lines are being read from a file.

[code removed]


for example the line ID which is "105:1:CME" is one sub string to be stored in a struct member variable called lineID. "20100601" to be stored in another struct variable called startTime and so on....

and also is there any way I can merge the date/time sub strings and store them in one struct member variable like this "20100601-07:34:22.796" that is removing the comma and putting a dash (-) between them instead of treating them as two different sub strings?

Thanks

Last edited on by admin
The getline() function you get from #including <string> does what you want.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
#include <sstream>
#include <string>

std::istream& operator >> ( std::istream& ins, mystruct_t& rec )
  {
  std::string s;
  std::getline( ins, s );

  std::istringstream ss( s );
  std::getline( ss, rec.first_string_item, ',' );
  ...

  return ins;
  }

For non-string-type items, you will need to read the string then convert it to the proper type using yet another stringstream.

Hope this helps.
Topic archived. No new replies allowed.