Can we specify variable field width in a scanf() format string? If possible how?

Showing Answers 1 - 2 of 2 Answers

Ajay K

  • Jul 1st, 2007
 

Yes . e.g. scanf ("%10s", str ); only 10 chars would be taken in

  Was this answer useful?  Yes

No, only a constant is acceptable. However, it is possible to construct the format string on fly with the desired field width, e.g.,

char format[20]; sprintf(format, "%%%ds", sizeof(buff)-1);

When I was a little boy, you could use "*" to indicate a variable field width. This gave useful code like:

char buff[20]
...
count = fscanf("%*s", sizeof(buff)-1, buff);

However, at some point this was removed from the ANSI C spec. "*" now means "ignore next option". See
http://flash-gordon.me.uk/ansi.c.txt
or
http://linux.about.com/library/cmd/blcmdl3_scanf.htm
or others.

Note also that in some system scanf is deprecated in favor of scanf_s. This function forces the programmer to supply buffer size.

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions