Lucia
Lucia

Reputation: 371

Parsing a string into multiple strings

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!!!

Upvotes: 2

Views: 772

Answers (2)

Kerrek SB
Kerrek SB

Reputation: 476930

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.

Upvotes: 2

pmg
pmg

Reputation: 108968

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.

Upvotes: 3

Related Questions