假设我必须输入 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/