doco
doco

Reputation: 43

Double doesn't scan properly

#include <stdio.h>

int main() {
  double a;
  char b[32];
  scanf("%31[^,] %lf", b, &a);
  printf("%s, %lf", b, a);
  return 0;
}

String b is stored properly, but variable a isn't. What is my error?

Upvotes: 4

Views: 96

Answers (1)

gsamaras
gsamaras

Reputation: 73366

Change this:

scanf("%31[^,] %lf", b, &a);

to this:

scanf("%31[^,], %lf", b, &a);

since the format %31[^,] reads until the comma, but does not read the comma itself, as commented. As a result, you need to add an additional comma.

This also explains why b gets populated as expected, because its the first variable to get filled. The issue starts after the comma, which explains why "a variable isn't stored properly".

As @pmg commented, you should really check the number of matches, which in your case is two. With your code, you'd have got a non-expected return value from the method, and realized that something is wrong in the format. Example:

if (scanf("%31[^,], %lf", b, &a) != 2)
  /* error */; 

Upvotes: 2

Related Questions