2

I have to split a string into several ones. In fact what i need is to parse some input from a file that is in the following format (i9, i9, i2) for example.

i9 means a decimal number as: (5blankspaces)4567

So i need to retrieve that numbers properly. The width is always fixed so every number must obey that. A correct instance of that format would be

(5spaces)4567(6spaces)453(1space)2 or (5spaces)4567(6spaces)45322 (where 22 is the argument for i2 in this case)

The white spaces before the numbers are giving me headache, so i thought i could split every argument into a character array and then convert it to integer since the %d specifier ignores all blank space and i dont know how to use the width as well as ignoring spaces.. (if this can be done, i mean, parsing all to integer please say so!!)

If not.. well, i would need help to parse every string into substring, so far i've done this but it's not working:

while (fgets(buffer, 600, f)) {
    sscanf(buffer, "%9[^\n]s %9[^\n]s %2[^\n]s", arg1, arg2, arg3);
    ....
}

Please, any help would be greatly appreciated!!!

Chuck Norris
  • 15,207
  • 15
  • 92
  • 123
Lucia
  • 361
  • 1
  • 7
  • 18

2 Answers2

3

This answer is C. That is why I used the variable name new.

Use strncpy() and terminate the result properly.

char part1[10], part2[10], part3[3];
const char *new = "     4567      45322\n"; /* the line read */

strncpy(part1, new, 9);    part1[9] = 0;
strncpy(part2, new+9, 9);  part2[9] = 0;
strncpy(part3, new+18, 2); part3[2] = 0;

I suggest you do not try to write multi-language source files.

pmg
  • 106,608
  • 13
  • 126
  • 198
  • 3
    Haha, `new` as a variable name is a great way to trip up all those Microsoft victims :-) – Kerrek SB Feb 03 '12 at 09:36
  • Thank you all for the answers!! everything worked fine, except for the following case: (2spaces)137411365101(3spaces)0.93 The real format is i7 i7 f7 but when it parses the 0.93 it stores (space)1(space)0.93 which is right (width 7) but it's not like this in the file (as i write above).. that 1 number shouldn't be there :S please help! – Lucia Feb 03 '12 at 10:58
  • Haha!! copying the code to show you i understand and fixed my error! it works like a charm, thank you all! :) – Lucia Feb 03 '12 at 11:36
2

In C++, use substr(), along with the usual string to integer conversions:

#include <string>

std::string s = "     1234      78922";

std::string s1 = s.substr(0, 9);
std::string s2 = s.substr(9, 9);
std::string s3 = s.substr(18);   // or substr(18, 2)

int n1 = std::stoi(s1), n2 = std::stoi(s2), n3 = std::stoi(s3);

Apply the usual length checks where appropriate to validate that the input is indeed in the correct format.

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084