Reputation: 1
I am trying to split up a string into 3 variables of type int,char,int. I have the following string to split 1000P3. I have the following code to do this but the char variable is containg the P3 instead of just the P.
int num1;
char type [10];
int num2 =0;
sscanf("1000P3","%d %c %d",&num1,type,&num2);
Any assistance would be grateful.
Upvotes: 1
Views: 141
Reputation: 23218
An array of char that is null terminated is a string, and its name happens to be a pointer to an address already. so you can just use:
char type[10];
you would use:
sscanf("1000P3","%d %s %d",&num1,type,&num2);
^ ^
A single char is treated just as you would an int. To read its value, pass the address of the variable using the &
operator.
So with
char type;
you would use:
sscanf("1000P3","%d %c %d",&num1,&type,&num2);
^ ^
Upvotes: 2
Reputation: 133919
%c
reads a single character, not a character string. That you saw 3 was just a coincidence from undefined behaviour. Try
int num1;
char type;
int num2;
sscanf("1000P3","%d %c %d", &num1, &type, &num2);
And remember to printf the character also with %c
.
Also you should check the return value of sscanf
; if it is not 3 (as we wanted to parse 3 items), then your input is incorrect.
Upvotes: 2