// filename:c2011-7-21-6-2-ex.c // original examples and/or notes: // (c) ISO/IEC JTC1 SC22 WG14 N1570, April 12, 2011 // C2011 7.21.6.2 The fscanf function // compile and output mechanism: // (c) Ogawa Kiyoshi, kaizen@gifu-u.ac.jp, December.29, 2013 // compile errors and/or wornings: // (c) Apple LLVM version 4.2 (clang-425.0.27) (based on LLVM 3.2svn) // Target: x86_64-apple-darwin11.4.2 //Thread model: posix // (c) LLVM 2003-2009 University of Illinois at Urbana-Champaign. #include #include int main(void) { // Example 1 /* ... */ int n, i; float x; char name[50]; n = fscanf(stdin, "%d%f%s", &i, &x, name); // with the input line: 25 54.32E-1 thompson printf("%d%f%s\n", i, x, name); // Example 2 //int i; float x; char name[50]; fscanf(stdin, "%2d%f%*d %[0123456789]", &i, &x, name); //with input: 56789 0123 56a72 printf("%d%f%s\n", i, x, name); // Example 6 char str[50]; fscanf(stdin, "a%s", str); printf("a%s\n", str); // Example 7 wchar_t wstr[50]; fscanf(stdin, "a%ls", wstr); printf("a%ls\n", wstr); //wchar_t wstr[50]; fscanf(stdin, "a↑ X↓%ls", wstr); printf("a%ls\n", wstr); // Example 3 int count; float quant; char units[21], item[21]; do { count = fscanf(stdin, "%f%20s of %20s", &quant, units, item); fscanf(stdin,"%*[^\n]"); printf("%f%20s of %20s\n", quant, units, item); } while (!feof(stdin) && !ferror(stdin)); // Example 4 int d1, d2, n1, n2, i2; i2 = sscanf("123", "%d%n%n%d", &d1, &n1, &n2, &d2); printf("%d%n%n%d%d\n", d1, &n1, &n2, d2,i2); // Example 5 //int n, i; n = sscanf("foo % bar 42", "foo%%bar%d", &i); return printf("7.21.6.2 The fscanf function %d\n", i); } // execution command is // ./a.out < c2011-7-21-6-2-ex.data // output may be //255.432000thompson //56789.00000056 //a72 //a //a //0.000000 of //2.000000 quarts of oil //-12.800000 degrees of oil //-12.800000 degrees of oil //10.000000 LBS of dirt //100.000000 ergs of energy //100.000000 ergs of energy //12301 //7.21.6.2 The fscanf function 56