简体   繁体   中英

Extracting numbers from a string in C++

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.

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).

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM