Reputation: 29
quote I have input something like
!Hello world! - 123 123 -
and I need to get it intostruct { char *string; int a; int b;}
Can you help me?
typedef struct {
int a;
int b;
char *string;
} Smth;
//-----------(size=(already known size of input))
Smth *smth = (*Smth)malloc(sizeof(smth));
smth.string = (char*)malloc(sizeof(char) * size);
sscanf(input, "!%[^!]! - %d %d - ", smth.string, &smth.a, &smth.b); // doesn't work for me
Upvotes: 0
Views: 64
Reputation: 2371
You are lacking the input string for sscanf
. See example below.
#include <stdio.h>
#include <stdlib.h>
typedef struct
{
int a;
int b;
char *string;
} Smth;
int main(void)
{
Smth smth;
sscanf(
"!Hello world! - 123 123 -",
"!%m[^!]! - %i %i -",
&smth.string,
&smth.a,
&smth.b);
printf("Str: `%s' a:%d b:%d\n", smth.string, smth.a, smth.b);
free(smth.string);
return 0;
}
UPDATE: Given your change in question
#include <stdio.h>
#include <stdlib.h>
typedef struct
{
int a;
int b;
char* string;
} Smth;
int main(void)
{
size_t size = 30u;
char input[] = "!Hello world! - 123 123 -";
Smth* smth = (Smth*) malloc(sizeof(Smth));
smth->string = (char*) malloc(sizeof(char) * size);
sscanf(input, "!%29[^!]! - %d %d - ", smth->string, &smth->a, &smth->b);
printf("Str: %s a:%d b:%d\n", smth->string, smth->a, smth->b);
free(smth->string);
free(smth);
return 0;
}
Upvotes: 2
Reputation: 32596
before you edit your question
the call
sscanf("!%[^!]! - %d %d - ",string,&a,&b);
is not the one you want, you missed to give the string to parse as the first argument, so the string to parse is the format you wanted to use and the used format is the perhaps not initialized value of string
You wanted :
#include <stdio.h>
int main()
{
char string[32];
int a,b;
const char * i = "!Hello world! - 123 123 -";
if (sscanf(i, "!%31[^!]! - %d %d - ", string,&a,&b) == 3)
printf("'%s' %d %d\n", string, a, b);
else
put("error");
return 0;
}
does the work :
pi@raspberrypi:/tmp $ gcc -Wall f.c
pi@raspberrypi:/tmp $ ./a.out
'Hello world' 123 123
pi@raspberrypi:/tmp $
Notice I added in your original format a max length for the read string to not take the risk to write out of string and then to have an undefined behavior. If you do not want to manage yourself the array for string you can use the option %m
but is not always available.
Upvotes: 2