为什么 Scanf 在拍摄角色时工作异常 [英] Why Scanf works wierd while taking a character

查看:12
本文介绍了为什么 Scanf 在拍摄角色时工作异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

程序说明:- 我编写了一个程序,它从用户无限号输入字符.次并打印输入的输入.这是程序

Program Explantion:- I have written a program which takes character input from the user infinite no. of times and print the entered input.Here is the program

#include<stdio.h>
int main()
{
int i=1;
char a;
  while (i!=0)
  {

   printf("Enter %d th value\n",i);
   scanf("%c",&a);
   printf("Entered input is %c\n",a);
    i++;
  }

}

上述程序的输出:-

Enter 1 th value
q
Entered input is q
Enter 2 th value
Entered input is 

Enter 3 th value
r
Entered input is r
Enter 4 th value
Entered input is 

Enter 5 th value
g
Entered input is g
Enter 6 th value
Entered input is 

Enter 7 th value

如您所见,程序跳过了偶数循环,并且它仅适用于奇数个i"值.

As you can see the program is skipping the even numbered loops and it is working for only odd number of 'i' values.

我做了什么:-

我在网上搜索了一整天,最后我发现我们必须在 scanf 中的 %c 之前插入空格.这是更新的程序.

I have searched the Internet my whole day and at last I found out that we have to insert space before %c in scanf.Here is the updated program.

 #include<stdio.h>
int main()
{
int i=1;
char a;
  while (i!=0)
  {

   printf("Enter %d th value\n",i);
   scanf(" %c",&a);   //changed lineeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee
   printf("Entered input is %c\n",a);
    i++;
  }

}

我没有任何区别,但我在 scanf 中的 %c 之前添加了空间.现在它工作正常.这是输出:-

I made no difference but I have added space before %c in scanf .Now it is working fine.Here is the output:-

Enter 1 th value
q
Entered input is q
Enter 2 th value
w
Entered input is w
Enter 3 th value
e
Entered input is e
Enter 4 th value
r
Entered input is r
Enter 5 th value

我的问题:-究竟发生了什么?我很想知道这个问题,谁能给我详细解释一下.我上网搜了下,没有找到关于这种问题的任何解释!!

My Question:- What is happening exactly? I am very eager to know about the problem.Can some one explain me in detail.I surfed through the internet but I did not find any explanation about this kind of problem!!

推荐答案

您将在缓冲区中留下一个换行符 \n 任何按 Enter 输入字符的内容.在每隔一次迭代 scanf 读取该换行符.

You are leaving a newline \n character in the buffer everything you press enter to input a character. On every other iteration scanf reads that newline.

" %c" %c 之前的空格将消耗包括换行符在内的空格.如果有的话.

" %c" the space before the %c will consume whitespace including the newline. if there is one.

这篇关于为什么 Scanf 在拍摄角色时工作异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆