c - 用于读取 Char 类型输入时 scanf 的不可预测行为。

标签 c char scanf

<分区>

我正在学习链表,当我使用 scanf 输入字符时,代码编译正常,但在运行时它不要求输入并跳过 scanf 语句。

#include<stdio.h>
#include<stdlib.h>
struct node
{
    int data;
    struct node *ptr;
};
struct node* allocate();
struct node* create();
void display(struct node*);
int main()
{
    struct node *new;
    new=create();
    display(new);
    return 0;
}
struct node* allocate()
{
    struct node *temp;
    temp=(struct node*)malloc(sizeof(struct node));
    return temp;
}
struct node* create()
{
    struct node *start,*next;
    char ch;
    start=next=allocate();
    printf("Enter data:\n");
    scanf("%d",&start->data);
    perror("store data");
    start->ptr=NULL;
R1: printf("Do you want to enter more data? y or n::    ");
    scanf("%c", &ch); //Check for error here
    if(ch=='y'||ch=='Y')
    {
        while(ch=='y'||ch=='Y')
        {
            next->ptr=allocate();
            next=next->ptr;
            printf("Enter data:\n");
            scanf("%d",&next->data);
            next->ptr=NULL;
            printf("Do you want to enter more data? y or n::    ");
            scanf(" %c",&ch);
        }
    }    
    if(ch=='n'||ch=='N')
    {
        return start;
    }
    else
    {
        printf("Please enter correct option.\n");
        goto R1;
    }
}
void display(struct node* temp)
{
    printf("%d\n",temp->data);
    while(temp->ptr!=NULL)
    {
        temp=temp->ptr;
        printf("%d\n",temp->data);
    }      
}

请看评论

Check for error here

在代码中知道我所指的语句。

  • 现在,如果我在格式说明符之前添加一个空格,即在 scanf 语句中的 %c 之前添加一个空格,那么我的代码可以正常运行。 .

    scanf(" %c",&ch);
    

当我使用 getchar 而不是 scanf 时,我遇到了同样的问题

ch=getchar();

当我在 scanf 语句中的格式说明符前没有使用空格或使用 getchar() 语句运行我的代码时,我的程序不要求输入。它在 ch 中不存储任何内容。 谁能解释一下背后的原因?为什么 scanf 对字符数据类型的行为如此不同?

附加信息:

  • 使用海湾合作委员会
  • Linux 内核 3.6.11-4
  • 操作系统 Fedora 16(64 位)
  • 英特尔 i5 处理器。

最佳答案

为什么 scanf 对字符数据类型的行为如此不同?

scanf() 行为不同,因为类型不同。

对于像 %i %u %e %f 这样的数字格式说明符,scanf() 会丢弃前导空格。所以“123”和“123”都读作123。

对于 %c,scanf() 接受 1 个字节的输入,任何 1 字节,并返回它,包括空格和\0。

使用 %s scanf() 就像扫描数字一样忽略前导空格。它扫描 chars 直到找到另一个空格。

格式说明符 %[...] 的工作方式与 %s 类似,因为它扫描多个 char,但“...”部分告诉要查找的内容。它不会抛出前导空格。

关于c - 用于读取 Char 类型输入时 scanf 的不可预测行为。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18498916/

相关文章:

c - 如何在 VS Code 调试 session 中持续观察变量及其值?

c# - 字符串 "a"不等于 C# 中的 Char "a"?

交换 scanf() 调用时 C 程序未完全执行

c - 有没有办法在 C 中读取一个 c 字符串,然后使用一个 scanf 读取一个 int?

c - 将文件名或标签链接到数字索引

c - 从客户端套接字获取命令序列

objective-c - 如何查明二进制文件是在哪个操作系统中使用终端编译的?

c - 返回单个字符的数组

c - 为什么 char[512] 的地址等于 char[512]

c - scanf() 将换行符保留在缓冲区中