scanf“额外输入"必需的 [英] scanf "extra input" required

查看:26
本文介绍了scanf“额外输入"必需的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于我编写的一些简单的硬件代码,我需要通过 scanf 函数获取 7 个参数:

for some simple HW code I wrote I needed to get 7 arguments via the scanf function:

scanf("%d %d %d %d\n", &vodka, &country, &life, &glut);
scanf("%d\n", &ageof);
scanf("%d\n", &dprice);
scanf("%d\n", &mprice);

如您所见,我要求按此顺序提供 7 个参数:

as you can see, I'm asking for 7 arguments in this order:

参数[空格] 参数[空格] 参数[空格] 参数(下行)

argument [space] argument [space] argument [space] argument (down line)

参数(下线)

参数(下线)

参数(下线)

但是,在运行代码时,我突然需要输入其中的 8 个,我不知道为什么....

BUT, when running the code, I'm suddenly required to input 8 of them, and I have no idea why....

对任何人有帮助吗?

推荐答案

@chqrlie 所述="https://stackoverflow.com/a/33905283/2410359">@Blue Moon 格式中的一个空格,可以是 ' ', '\n''\n' 或任何空格都做同样的事情.它指示 scanf() 使用空格,例如 '\n' 来自 Enter,直到检测到非空格.然后将该非空白字符放回 stdin 以进行下一个输入操作.

As explained by @chqrlie and @Blue Moon a white space in the format, be it ' ', '\n', '\n' or any white-space does the same thing. It directs scanf() to consume white-space, such as '\n' from an Enter, until non-white-space is detected. That non-white-space character is then put back into stdin for the next input operation.

scanf("%d\n", ...) 直到在 int 之后输入一些非空格后才返回.因此需要第 8 个输入.第 8 个输入未被消耗,但可用于后续输入.

scanf("%d\n", ...) does not return until some non-white space is entered after the int. Hence the need for the 8th input. That 8th input is not consumed, but available for subsequent input.

阅读 4 行输入的最佳方法是……鼓卷……阅读 4 .然后处理输入.

The best way to read the 4 lines of input is to .... drum roll ... read 4 lines. Then process the inputs.

char buf[4][80];
for (int i=0; i<4; i++) {
  if (fgets(buf[i], sizeof buf[i], stdin) == NULL) return Fail;
}
if (sscanf(buf[0], "%d%d%d%d", &vodka, &country, &life, &glut) != 4) {
  return Fail;
}
if (sscanf(buf[1], "%d", &ageof) != 1) {
  return Fail;
}
if (sscanf(buf[2], "%d", &dprice) != 1) {
  return Fail;
}
if (sscanf(buf[3], "%d", &mprice) != 1) {
  return Fail;
}
// Use vodka, country, life, glut, ageof, dprice, mprice
return Success

这篇关于scanf“额外输入"必需的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆