简体   繁体   中英

Extract int from char* containing special character in Ubuntu gcc

I have a char* buf[] which when printed looks like (-1.20112344x-2.13413423):2 . I need to extract the two int s inside this char* buf[] which are inside the () and separated by the special character x . The int may be positive or negative (what I gave as an example is a specific case).

I am compiling using GCC on Ubuntu. Please show me how to do so considering how I am compiling.

If I understand your question correctly, the following program should help (edited following the comment by paxdiablo - using double rather than float type, and returning the result to 8 significant figures).

include <stdio.h>
int main(void) {
  char* s=" (-1.20112344x-2.13413423):2 ";
  double a, b;
  sscanf(s, " (%lfx%lf", &a, &b);
  printf("a is %.8lf; b is %.8lf\n", a, b);
}

When run, this returns

a is -1.20112344; b is -2.13413423

The sscanf function scans a string for numbers following the format given - in this case, the format string " (%lfx%lf" says: "skip a space-open-bracket ( , then read a double %lf , putting the result in the location pointed to by the address of a: &a (ie put the result in a ). Skip the x , then find another double and store the result in b .

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