承认;“空间”;及;输入“;用scanfc

承认;“空间”;及;输入“;用scanfc,c,C,我需要识别作为输入的字符是空格还是回车。 我知道enter是十六进制的“0x0A”,而space是“0x20”,但我不知道为什么scanf似乎无法识别空格 while ( (error=scanf("%d", &stop) )== EOF && error==0 ) printf("Error while reading the value input, try again\n"); ...(some code)... whil

我需要识别作为输入的字符是空格还是回车。 我知道enter是十六进制的“0x0A”,而space是“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”中,我希望用户插入一个通用值,在第二个“while”中,我检查值是否为“ENTER”,而“if”则检查是否插入了“SPACE”。 如果我按空格键,就会出现分割错误,不知道为什么:s

编辑:

我根据我在评论中读到的内容编写了这个新示例:

#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;
}
节目结束了

为什么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)...
 }
scanf()
可以识别空格,但不能识别 使用
scanf(“%d”,&stop)
作为
“%d”
首先消耗并丢弃所有前导空格

“%c”
不会丢弃前导空格。读取一个字符


由于OP似乎有兴趣使用
scanf()
一次读取和测试一个字符,同时检测一个罕见的输入错误,可能还有文件结尾:

// Read one character.
// Return 1 on success.
// Return EOF on end-of-file.
// Return 0 on rare input error.
int read1(char *dest) {
  if (scanf("%c", dest) == 1) return 1;
  if (feof(stdin)) return EOF;
  return 0;
}

需要识别作为输入的字符是空格还是ENTER

fgets()
是读取一行用户输入的更好方法

char buf[100];
if (fgets(buf, sizeof buf, stdin)) {
  // Use buf
}  

请注意,由于
EOF
常数不会被定义为零(通常为-1),因此
error
(在您的第一个
中,而
)不能同时是
EOF
&&
0
。如果您需要了解空格,请不要使用
scanf()
和family。除非您使用
%c
%[…]
(扫描集)或
%n
error=scanf(
非常奇怪。
scanf
返回匹配条目的数量,因此您希望
scanf(“%d”,…)
在正常操作中返回1。
而(
在文件结束时是一个无限循环。应在文件结束时中断循环。@finleyams“triggered”不清楚。
scanf(“%c”,&input)
执行每次迭代。在文件条件结束时,它会反复返回
EOF
。我只需要读一个字符,但谢谢,也许我将来会使用它!第三行是什么?@finleyams不清楚“第三行”。哪一行?可能复制/粘贴在注释中这一行:if(feof(stdin))return EOF;@finleyams当输入函数返回
EOF
时,这是由于输入错误(例如键盘死机)、文件结束之前发生过、文件结束刚刚发生。
feof(stdin)
在后两种情况下返回非零(true)。@finleyams节省时间,启用所有警告。
int read1(char*dest)字符输入;读取1(输入);
应投诉。