Hello,

this is my file format:

MP,EX,1,1.081048e+10
MP,ALPX,1,9.600000e-06, 3, 2.3
MP,NUXY,1,3.000000e-01
CX,DENS,1,2.797598e-01
BT,KXX,1,6.752689e+02
MP,C,1,3.448000e+05

I want to extract first sring, then second, then I want to extract all numbers in to a float till I come newline, there could be up to 10 values. How do I extract if my input is separted by comma instead of space?

Recommended Answers

All 3 Replies

Use getline to read each string, setting the delimiter to be the comma character. Then loop through reading in the floating point values, each read will halt at the first non-numeric char (comma or newline). Then read the next character into char, test that char to determine if it's the newline ( '\n' ) character. If not, read again, otherwise you're done. I think an array to store the floating point values is a good choice here.

That makes sense, thank you, so use getline, to pull out two sub strings, then extract ">>" the values, but I forgot to mention that at the begining of each new line there could be from one to four string commands before the values come up. Any way to use both ',' and '\n' as separator? Here is what I do now, but I would like to extract the srtings and characters with minimal processing time, so I would like to avoid the stringstream and replacing ',' with ' '.

char input_line[200];
char substr[8];
ifstream inpdeck;
istringstream string_stream;
inpdeck.open("file.txt");
if (inpdeck.good()) cout << endl << "Opened the file" << endl;
  while(inpdeck.getline(input_line, 200, '\n')){
    // replace commas with spces.
    while(strchr(input_line,','))
      *strchr(input_line,',') = ' ';
      string_stream.str(input_line); // place the string on to string stream
      string_stream >> substr; // extract the command

Thank you...

You could read in every comma separated item as a string, then attempt to convert it to a numeric value (several methods available, google is your friend). Anything that doesn't convert, consider it a text item.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.