Why "% d" is not equivalent to "% d" as a format string in scanf

I am reading a book and will solve some problems. Question:

For each of the following pairs of format strings, scanfspecify whether or not the two strings are the same. If not, show how they can be distinguished.

(a) "%d"veruss" %d"

(b) "%d-%d-%d"compared to"%d -%d -%d"

(c) "%f"compared with"%f "

(d) "%f,%f"compared to"%f, %f"

My solution (a) is equivalent as it scanfcasts a blank. For (b) they are not equivalent, since it scanfmatches -with a space . For (c) they are not equivalent since they scanfwill return the empty space to the buffer. For (d), they are equivalent, since it scanfleaves a blank. According to Chegg's decisions, all the previous questions are not equivalent. Am I mistaken? In this post, I would like to make sure my answers are correct compared to Chegg solutions. I already read the book, and I have decent knowledge of scanf.

+4
source share
2 answers

"%d"and are the " %d"same for OP reasoning.

, , , "123" " 456". , FILE , "abc" " xyz"? "%d" , . .

... : C11dr ยง7.21.6.2 7

... , [, c n. ยง7.21.6.2 8

( "%d").

.

void next_testi(const char *s, const char *fmt, const char *pad) {
  rewind(stdin);
  int i = 0;
  int count = scanf(fmt, &i);
  int next = fgetc(stdin);
  printf("format:\"%s\",%s count:%2d, i:%2d, next:%2d, text:\"%s\"\n", //
      fmt, pad, count, i, next, s);
}

void next_test(const char *s) {
  FILE *fout = fopen("test.txt", "w");
  fputs(s, fout);
  fclose(fout);

  freopen("test.txt", "r", stdin);
  next_testi(s, "%d", " ");
  next_testi(s, " %d", "");
  puts("");
}

int main() {
  next_test("3");
  next_test(" 4");
  next_test("");
  next_test(" ");
  next_test("+");
  next_test(" -");
  next_test("X");
  next_test(" Y");
}

format:"%d",  count: 1, i: 3, next:-1, text:"3"  // scanf() return value 1:success
format:" %d", count: 1, i: 3, next:-1, text:"3"

format:"%d",  count: 1, i: 4, next:-1, text:" 4"
format:" %d", count: 1, i: 4, next:-1, text:" 4"

format:"%d",  count:-1, i: 0, next:-1, text:""  // scanf() return value EOF, next is EOF
format:" %d", count:-1, i: 0, next:-1, text:""

format:"%d",  count:-1, i: 0, next:-1, text:" "
format:" %d", count:-1, i: 0, next:-1, text:" "

format:"%d",  count: 0, i: 0, next:43, text:"+" // scanf() return value 0
format:" %d", count: 0, i: 0, next:43, text:"+"

format:"%d",  count: 0, i: 0, next:45, text:" -"
format:" %d", count: 0, i: 0, next:45, text:" -"

format:"%d",  count: 0, i: 0, next:88, text:"X"
format:" %d", count: 0, i: 0, next:88, text:"X"

format:"%d",  count: 0, i: 0, next:89, text:" Y"
format:" %d", count: 0, i: 0, next:89, text:" Y"
+1

, (c) .

"scanf ."

, scanf() , %f , , .

C11, ยง7.21.6.2

, () , ( ) . .

0

Source: https://habr.com/ru/post/1674299/


All Articles