【发布时间】:2020-10-21 15:59:45
【问题描述】:
我需要识别作为输入的字符是空格还是回车。 我知道输入是十六进制的“0x0A”,而空格是“0x20”,但我不知道为什么scanf似乎无法识别空格。
while ( (error=scanf("%d", &stop) )== EOF && error==0 )
printf("Error while reading the value input, try again\n");
...(some code)...
while ( stop!= 0x0A )
{
if (stop == 0x20) {
printf("Going to fill the line\n");
...(some code)...
}
在第一个“while”中,我希望用户插入一个通用值,在第二个中,我检查该值是否为“ENTER”,而“if”检查是否已插入“SPACE”。 如果我按“SPACE”,则会出现分段错误,不知道为什么:S
编辑:
我根据在 cmets 中阅读的内容编写了这个新示例:
#include <stdio.h>
#include <stdlib.h>
void main()
{
char input;
int error =0;
printf("I want to read only numbers\n"
"Let's start!\n");
while ( (error=scanf("%c", &input) )== EOF || error==0 )
printf("Error while reading the input, maybe Enter was pressed try again\n");
printf("input is : %c \n",input);
printf("Taking new input : \n");
while (input != "\n")
{
if (input == 0x20)
break;
printf("Taking New input : \n");
while ( (error=scanf("%c", &input) )== EOF || error==0 )
printf("Error while reading the input, maybe Enter was pressed try again\n");
printf("New input is : %c \n",input);
}
return;
}
这是输出:
I want to read only numbers
Let's start!
7
input is : 7
Taking New input :
New input is :
程序结束。
【问题讨论】:
-
请注意,
EOF常量将不定义为零(通常为 -1),然后是error(在您的第一个while中)不能同时是EOF&&0。 -
如果您需要了解空白,请不要使用
scanf()和家人。除非您使用%c、%[…](扫描集)或%n,否则它们会跳过空白。 -
error = scanf(是非常奇怪。scanf返回匹配条目的数量,因此您会期望scanf("%d",..)在正常操作中返回 1。 -
while ( (error=scanf("%c", &input) )== EOF || error==0 ) printf("Error while reading the input, maybe Enter was pressed try again\n");是文件结束时的无限循环。应该在文件结束时跳出循环。 -
@FinleyAdams “触发”尚不清楚。
scanf("%c", &input)执行每次迭代。在文件结束的情况下,它会重复返回EOF。
标签: c