简体   繁体   English

C 语言:Scanf

[英]C Language: Scanf

This is a simple C program that explains do while loop.Before the loop ends there two scanf./ I am really confused with the one " scanf("%d",&dummy); ".这是一个简单的 C 程序,它解释了 do while 循环。在循环结束之前有两个 scanf。/我真的对一个“scanf(”%d",&dummy);“感到困惑。 The program will not run as expected wihtout this line.没有这一行,程序将无法按预期运行。 So, I believe this line act as a some sort of placeholder to create a space to take input for chat.所以,我相信这条线作为某种占位符来创建一个空间来接受聊天输入。 But I am not sure about this and how actually it works但我不确定这一点以及它实际上是如何工作的

#include<stdio.h>  
#include<stdlib.h>  
void main ()  
{  
    char c;  
    int choice,dummy;    
    do{  
    printf("\n1. Print Hello\n2. Print Javatpoint\n3. Exit\n");  
    scanf("%d",&choice);  
    switch(choice)  
    {  
        case 1 :   
        printf("Hello");   
        break;  
        case 2:    
        printf("Javatpoint");  
        break;  
        case 3:  
        exit(0);   
        break;  
        default:   
        printf("please enter valid choice");      
    }  
    printf("do you want to enter more?");   
    scanf("%d",&dummy);  //This part confuses me
    scanf("%c",&c);  
    }while(c=='y');  
}  

Once the user has entered a choice and hit Enter key, the number is read up to, but not including, the end-of-line character.一旦用户输入一个选项并按下Enter键,该数字将被读取到行尾字符,但不包括行尾字符。 Without this scanf("%d", %dummy);没有这个scanf("%d", %dummy); , that end-of-line character is still there and is read into c . ,该行尾字符仍然存在并被读入c Since that is not equal to 'y' , your loop terminates.由于这不等于'y' ,因此您的循环终止。

With the scanf("%d", dummy);scanf("%d", dummy); call, the whitespace gets consumed looking for digits.调用时,空格会被消耗以寻找数字。 Note that scanf documentation says, "All conversion specifiers other than [, c, and n consume and discard all leading whitespace characters (determined as if by calling isspace) before attempting to parse the input."请注意, scanf 文档说:“除 [、c 和 n 之外的所有转换说明符,在尝试解析输入之前都会消耗并丢弃所有前导空白字符(就像通过调用 isspace 一样确定)。” When a non-whitespace, non-digit character is encountered (such as 'y' or 'n'), the reading of the integer fails.当遇到非空白、非数字字符(例如“y”或“n”)时,integer 的读取失败。 That's ok, you're ignoring it anyway.没关系,反正你无视。 But now the 'y' or 'n' is there to read into c .但是现在“y”或“n”可以读入c

An easier way would be to change scanf("%c", &c);更简单的方法是更改scanf("%c", &c); to scanf(" %c", &c);scanf(" %c", &c); (note the space before %c ). (注意%c之前的空格)。 This tells scanf to consume any whitespace before reading a character into c .这告诉scanf在将字符读入c之前消耗任何空格。 It's much more idiomatic.它更加地道。

Because variable dummy is used to capture the return following choice number.因为变量dummy用于捕获选择数之后的return值。

If we add one line to print dummy如果我们添加一行来打印虚拟

    printf("[%c]\n", dummy); // We should change dummy's type to char, omit here

This is an explanation of the result:这是对结果的解释:

1. Print Hello                
2. Print Javatpoint
3. Exit
1                                     # This is input: 1 and an invisible return
Hellodo you want to enter more?[      # return is captured by scanf and printed
]
y                                     # This is input: y and an invisible return, return is ignored by scanf("%d", &choice), because it need numbers

1. Print Hello
2. Print Javatpoint
3. Exit
2                                     # This is input: n and an invisible return
Javatpointdo you want to enter more?[
]
n

This is happening as scanf leaves a '\n' character which is read by next scanf is %c is used.发生这种情况是因为 scanf 留下了一个 '\n' 字符,该字符由下一个 scanf 读取,使用 %c。

Solution: replace %c by %1s in the reported program to solve the issue (to read the next non-white space character, use %1s instead of %c).解决方案:将报告程序中的 %c 替换为 %1s 以解决问题(要读取下一个非空白字符,请使用 %1s 代替 %c)。

Kindly refer below program to see issue because of newline character.由于换行符,请参考下面的程序来查看问题。

[root@localhost Programs]# cat -n scan.c [root@localhost 程序]# cat -n scan.c

 #include<stdio.h>  
 #include<stdlib.h>  
 int main ()  
 {  
     char c = 0;  
     int choice,dummy;    
     do{  
     printf("\n1. Print Hello\n2. Print Javatpoint\n3. Exit\n");  
     scanf("%d",&choice);  
     switch(choice)  
     {  
         case 1 :   
         printf("Hello\n");   
         break;  
         case 2:    
            printf("Javatpoint\n");  
            break;  
            case 3:  
            exit(0);   
       break;  
            default:   
            printf("please enter valid choice\n");      
        }  
        printf("say 'y' if you want to enter more\n");   
        scanf("%c",&c);
        printf("%d\n",c);
        scanf("%c",&c);
        printf("%d\n",c);
        }while(c=='y');  
        return 0;
    }  

you can see value 10 which is the value of character '\n' left by earlier scanf.您可以看到值 10,它是早期 scanf 留下的字符 '\n' 的值。

  • Issue is resolved by below program (%1s is used in place of %c ):问题由以下程序解决(使用 %1s 代替 %c ):

    #include<stdio.h> #include<stdio.h>
    #include<stdlib.h> #include<stdlib.h>
    int main ()主函数()
    { {
    char c = 0;字符 c = 0;
    int choice,dummy; int 选择,假人;
    do{做{
    printf("\n1. Print Hello\n2. Print Javatpoint\n3. Exit\n"); printf("\n1. Print Hello\n2. Print Javatpoint\n3. Exit\n");
    scanf("%d",&choice); scanf("%d",&choice);
    switch(choice)开关(选择)
    { {
    case 1:情况1:
    printf("Hello\n"); printf("你好\n");
    break;休息;
    case 2:案例2:
    printf("Javatpoint\n"); printf("Javatpoint\n");
    break;休息;
    case 3:案例3:
    exit(0);退出(0);
    break;休息;
    default:默认:
    printf("please enter valid choice\n"); printf("请输入正确的选择\n");
    } }
    printf("say 'y' if you want to enter more\n"); printf("如果你想输入更多就说'y'\n");
    scanf("%1s",&c); scanf("%1s",&c); }while(c=='y'); }while(c=='y');
    return 0;返回0; } }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM