Matam Matam - 1 year ago 97
C Question

Scanf with a specific format

I would like to allow the user to only put input in a specific format.
The format:

for example. Spaces are allowed inbetween the commas and the characters.
I'm using:
if (scanf("a=%lf,b=%lf,c=%lf",&a,&b,&c) == 1)
but for some reason it doesn't work. How can I fix it?

Answer Source

You are converting 3 numbers, the return value should be 3 if all conversions are successful. Also note that %lf ignores spaces before the number. If you also want to ignore spaces around the , and before the = or the a, add a space in the format string:

double a, b, c;

if (scanf(" a =%lf , b =%lf , c =%lf", &a, &b, &c) == 3) {
    /* conversion was successful, 3 numbers parsed */

Note however that scanf() will not ignore just space characters, it will ignore and whitespace characters, including newlines, tabs, etc.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download