Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read string and various integers in same line in C

Tags:

c

scanf

I have a string called buffer which has the following data stored:
Rb [7, 0] 64

Using sscanf(), I'd like to do the following:

  • Read Rb and store it in a string called name
  • Read 7 and store it in an int variable called posx
  • Read 0 and store it in an int variable called posy
  • Read 64 and store it in a int variable called battery_level

I tried the following, but it doesn't work:

sscanf(buffer, "%s[^\ ] [%d,%d] %d", name, &posx, &posy, &battery_level);
like image 951
tsuo euoy Avatar asked Oct 20 '25 01:10

tsuo euoy


2 Answers

Problems that I see:

  1. "\ " is not a valid escape sequence.
  2. "%s[^ ]" does not do what you are expecting it to do. You need to use "%[^ ]".

You can use

sscanf(buffer, "%s [%d,%d] %d", name, &posx, &posy, &battery_level);

or

sscanf(buffer, "%[^ ] [%d,%d] %d", name, &posx, &posy, &battery_level);

Both of them work. See working code at http://ideone.com/QNuQuY

like image 173
R Sahu Avatar answered Oct 21 '25 14:10

R Sahu


Hope that it helps you.

I wrote a code, where the inputs will be divided by the first space ' ' sign, you can use other characters also, and improving this logic you can get your desired result:

#include <stdio.h>
int main()
{
    char buffer[] = "Rb [7, 0] 64";
    int posx, posy, batttery_level
    sscanf(buffer, "%[^ ] [%d,%d] %d", name, &posx, &posy, &battery_level);
    printf("%s [%d,%d] %d\n", name, posx, posy, battery_level);
    return 0;
}
like image 30
Subinoy Avatar answered Oct 21 '25 16:10

Subinoy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!