How to use scanf width specifier for 0?
1) unlimited width (see cywin gcc 4.5.3 Version)
2) UB
3) something else?
My application (not shown) dynamically generates a width specifier as part of a larger format string for scanf (). Rarely would this create "%0s" in the middle of a format string. In this context, the destination string for this %0s has only 1 byte of room for scanf() to store \0 , which with behavior # 1 above causes problems.
Note. The following test cases use persistent formats.
#include <memory.h> #include <stdio.h> void scanf_test(const char *Src, const char *Format) { char Dest[10]; int NumFields; memset(Dest, '\0', sizeof(Dest)-1); NumFields = sscanf(Src, Format, Dest); printf("scanf:%d Src:'%s' Format:'%s' Dest:'%s'\n", NumFields, Src, Format, Dest); } int main(int argc, char *argv[]) { scanf_test("1234" , "%s"); scanf_test("1234" , "%2s"); scanf_test("1234" , "%1s"); scanf_test("1234" , "%0s"); return 0; }
Output:
scanf:1 Src:'1234' Format:'%s' Dest:'1234' scanf:1 Src:'1234' Format:'%2s' Dest:'12' scanf:1 Src:'1234' Format:'%1s' Dest:'1' scanf:1 Src:'1234' Format:'%0s' Dest:'1234'
My question is about the last line. Width 0 seems to lead to a width limit, not a width of 0. If this is the correct behavior or UB, will I have to approach the situation with zero width in a different way or are there other scanf () formats to consider?
chux
source share