tsuo euoy
tsuo euoy

Reputation: 139

Read string and various integers in same line in C

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:

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

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

Upvotes: 4

Views: 3968

Answers (2)

Subinoy
Subinoy

Reputation: 488

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;
}

Upvotes: 1

R Sahu
R Sahu

Reputation: 206567

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

Upvotes: 3

Related Questions