c - 如果在 C 中空格后输入的输入无效,如何终止 Scanf()?

标签 c

假设我必须输入 3 个输入,并用空格分隔。 让它成为“3 4 5”。 现在,如果用户输入“3 10 5”并且只接受单个数字作为约束

我想让 scanf() 在输入空格后 10 后终止。

请帮忙。

最佳答案

最好使用 fget() 读取用户输入的

<小时/>

... to make scanf() terminate after 10 when space entered ...

scanf() 并不是解决此任务的最佳工具。

通过空格,我认为OP会容忍空白,其中包括空格、制表符。换行等。

请记住,stdin 通常是行缓冲的,但要在无效数字(超过 1 位)后停止 scanf(),代码需要限制或跟踪输入的字符数。 “10” 将失败,“00” 将失败,“+1” 将失败,“7” 将通过。

// read 1 `int` at a time.
// Use %n to record the offset of the scan up to that point
int left, right, n;

//               +--==------ consume white-spaces
//               | +-------- Record offset
//               | | +------ Record `int`
//               | | | +---- Record offset
int cnt = scanf(" %n%d%n", &left, &n, &right);
if (cnt == 1 && right == left + 1) {
  Success();
} else {
  Fail();
}

其他 scanf() 方法可能以 "%1[0-9]%c" 开头(测试 2nd 是否为空格)或 "% 1d%c"

关于c - 如果在 C 中空格后输入的输入无效,如何终止 Scanf()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44836377/

相关文章:

c - 使用 Windows 32 位串行通信时程序挂起

我可以只使用 percolateDown 实现堆吗?

c - 为什么 scanf llu 不验证 %llu?

c - c中的strcat模拟

python - 把python代码翻译成c代码有那么难吗?

c - 显示无边框图片并退出纯c

c - 仅在 C 中使用指针打印字符串数组

c - 如何将for循环转换为while循环?

需要显式调用 free() 的 C 函数

c - 如何从C中的字符中删除空行?