【问题标题】:Recognize "space" and "enter" with scanf C用scanf C识别“空格”和“输入”
【发布时间】: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", &amp;input) )== EOF || error==0 ) printf("Error while reading the input, maybe Enter was pressed try again\n"); 是文件结束时的无限循环。应该在文件结束时跳出循环。
  • @FinleyAdams “触发”尚不清楚。 scanf("%c", &amp;input) 执行每次迭代。在文件结束的情况下,它会重复返回EOF

标签: c


【解决方案1】:

为什么 scanf 似乎无法识别空格。

scanf() 可以识别空格,但不能 很容易使用scanf("%d", &amp;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;
}

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

fgets() 是一种非常更好的方法来读取用户输入。

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

【讨论】:

  • 我只需要读取一个字符,但谢谢,也许我将来会使用它!第三行是做什么的?
  • @FinleyAdams 不清楚“第三行”。哪条线?也许在评论中复制/粘贴
  • 这个:if (feof(stdin)) return EOF;
  • @FinleyAdams 当输入函数返回EOF时,这是由于输入错误(例如键盘死机),文件结束之前发生过,结束-文件刚刚发生。 feof(stdin) 在后两种情况下返回非零 (true)。
  • @FinleyAdams 节省时间,启用所有警告。 int read1(char *dest); .... char input; read1(input); 应该投诉。
猜你喜欢
  • 2014-10-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-23
  • 2020-05-24
  • 1970-01-01
  • 2010-11-17
相关资源
最近更新 更多