Stefan Stefanescu Stefan Stefanescu - 1 month ago 10
C Question

C sscanf not working with float

In the following code

scanf("%s", input);
sscanf(input," %s %f ", change, &grades);
printf("%s\n", change);
printf("%f", grades);


grades will be printed as
0.00
, no matter the input. Why doesn't
sscanf
recognise float format?

Answer

The first call to scanf is looking for a sequence of characters delimited by whitespace. If your input looks something like this:

test 98.3

Then input will only contain the string test.

If you want to read a full line of text so you can later parse it with sscanf, use fgets instead which will read a line:

char input[100];
char change[10];
float grades;

fgets(input, 100, stdin);
sscanf(input," %s %f ", change, &grades);
printf("%s\n", change);
printf("%f", grades);

Input:

test 96.5

Output:

test
96.500000
Comments