1

Suppose I have the following char array:

char *word="R12_X8_10";

The number of digits are not fixed but the locations with respect to the non-numeric characters are fixed. How can I extract the numbers without boost? I should get {"12", "8", "10"} by splitting the word.

This is supposed to be an easy task as I have done in Java many times but the in C++ it is taxing my brain.

DeiDei
  • 10,205
  • 6
  • 55
  • 80
Hassan
  • 157
  • 1
  • 12

2 Answers2

3

The C++ stream way would be to get or simply ignore the marking characters. For example to ignore them you could use:

const char *word = "R12_X8_10";
int i, j, k;
std::stringstream ss(word);

ss.ignore(1) >> i;
ss.ignore(2) >> j;
ss.ignore(1) >> k;

or even (more compact if not more readable):

((ss.ignore(1) >> i).ignore(2) >> j).ignore(1) >> k;

(unrelated, but note the const for word because a string litteral should not be assigned to a non const pointer).

Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252
2

You can try this.

int a,b,c;
char *word="R12_X8_10";
    sscanf(word,"R%d_X%d_%d",&a,&b,&c);

I know this is a c++ system, but I also know that scanf and sscanf work with c++ compiler if stdio.h in included.

I hope this helps.

Nitro
  • 1,063
  • 1
  • 7
  • 17
  • `sscanf()` works in C++ all right, but `char *word = "...";` does not. And header should be – Slava May 16 '18 at 14:53
  • You are right, I just tried it. Point is Hassan is not going to declare the string that way. It's just an example – Nitro May 16 '18 at 14:56
  • @Nitro, your suggestion is a good and easy one. I can convert the *char to std::string if needed. Thanks. – Hassan May 16 '18 at 14:59