加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

为什么“%d”不等同于“%d”作为scanf中的格式字符串

发布时间:2020-12-16 07:20:53 所属栏目:百科 来源:网络整理
导读:我正在读一本书并解决一些问题.问题是 For each of the following pairs of scanf format strings,indicate whether or not the two strings are equivalent. If they’re not,show how they can be distinguished. (a) "%d" veruss " %d" (b) "%d-%d-%d" ve
我正在读一本书并解决一些问题.问题是

For each of the following pairs of scanf format strings,indicate
whether or not the two strings are equivalent. If they’re not,show
how they can be distinguished.

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

(b) "%d-%d-%d" versus "%d -%d -%d"

(c) "%f" versus "%f "

(d) "%f,%f" versus "%f,%f"

我的解决方案是(a)它们是等价的,因为scanf丢弃了空白区域.对于(b)它们不等同,因为scanf匹配 – 具有空格.对于(c),它们不等效,因为scanf会将缓冲区中的空白区域放回.对于(d),它们是等价的,因为scanf丢弃白色空间.根据Chegg解决方案,所有前面的问题都不相同.我错了吗?在这篇文章中,我想确保我的答案与Chegg解决方案相比是正确的.我已经读过这本书了,而且我对scanf有很好的了解.

解决方法

根据OP的推理,“%d”和“%d”是相同的.

它们肯定与预期的数字输入相同,如“123”和“456”.剩下的考虑因素是FILE指针失败的地方,如“abc”与“xyz”一样? “%d”本身首先消耗领先的白色空间.所以没有区别.

… A conversion specification is executed in the following steps: C11dr §7.21.6.2 7

Input white-space characters … are skipped,unless the specification includes a [,c,or n specifier. §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",text:"3"

format:"%d",i: 4,text:" 4"
format:" %d",text:" 4"

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

format:"%d",text:" "
format:" %d",text:" "

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

format:"%d",next:45,text:" -"
format:" %d",text:" -"

format:"%d",next:88,text:"X"
format:" %d",text:"X"

format:"%d",next:89,text:" Y"
format:" %d",text:" Y"

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读