简体   繁体   English

C-使用scanf()时额外输入新行

[英]C - Extra new line input while using scanf()

I have the below 'C' code for a Console Win32 application using Visual Studio. 对于使用Visual Studio的Console Win32应用程序,我具有以下“ C”代码。 It checks for arguments and directly calls a function or gets inputs using scanf() and then calls the function. 它检查参数并直接调用函数或使用scanf()获取输入,然后调用该函数。 The program works perfectly if I give command line arguments, but when I give inputs using scanf() , it probably adds an extra new line character which I want to avoid. 如果我提供命令行参数,该程序可以完美运行,但是当我使用scanf()提供输入时,它可能会添加一个我想避免的额外的换行符。

I know it does this because when I give arguments, after showing 'Press ENTER to quit...', it waits for the ENTER input, but doesn't do so when using scanf() . 我知道这样做是因为,当我给出参数时,显示“按ENTER退出...”后,它会等待ENTER输入,但在使用scanf()时不会这样做。 This problem occurs if I use scanf_s() too. 如果我也使用scanf_s()则会出现此问题。

Appreciate your help on this. 感谢您的帮助。

Regards, 问候,

Shahid 沙希德

    unsigned long int ipv;
    unsigned int yrs;
    float acr, acl, asp, irr, psp;

        if(argc<=1) {
            //get inputs
            printf("Initial value of portfolio: "); scanf("%lu", &ipv);
            printf("Average cash rate: "); scanf("%f", &acr);
            printf("Average cost of living: "); scanf("%f", &acl);
            printf("Average return for share portfolio: "); scanf("%f", &asp);
            printf("Initial removal for living expenses: "); scanf("%f", &irr);
            printf("Percentage of shares in initial portfolio: "); scanf("%f", &psp);
            printf("Years for the analysis: "); scanf("%u", &yrs);

            //simulate the investment with given inputs
            simulate(ipv, acr, acl, asp, irr, psp, yrs);
        } else {
            if (argc == 8) {
                //invsim 1000000 0.05 0.036 0.12 0.08 0.5 20

                //simulate the investment with given inputs
                simulate(atol(argv[1]), (float)atof(argv[2]), (float)atof(argv[3]), (float)atof(argv[4]), (float)atof(argv[5]), (float)atof(argv[6]), atoi(argv[7]));
            } else {
                printf("Please enter arguments as...\ninvsim.exe ipv acr acl asp irr psp yrs");
            }
        }

printf("\n\nPress ENTER to quit...");
getchar();

I know it does this because when I give arguments, after showing 'Press ENTER to quit...', it waits for the ENTER input, but doesn't do so when using scanf(). 我知道这样做是因为,当我给出参数时,显示“按ENTER退出...”后,它会等待ENTER输入,但在使用scanf()时不会这样做。

That is the right behaviour, isn't it? 这是正确的行为,不是吗? When you supply arguments via command line, you're not pressing any ENTER key. 通过命令行提供参数时,无需按任何ENTER键。 So, there is no \\n in the input buffer. 因此,输入缓冲区中没有\\n So, getchar() will wait for the input from stdin . 因此, getchar()将等待来自stdin

However, when you intake values using scanf() , you press the ENTER key after the inputs. 但是,当您使用scanf()输入值时,请在输入后按ENTER键。 For numerical values, the numeric value is scanned but the \\n (produced by hitting ENTER )is remained in the input buffer to be read by next getchar() . 对于数值,将扫描数值,但是\\n (通过按ENTER产生)保留在输入缓冲区中,以供下一个getchar()读取。 So, your code doesn't wait . 因此,您的代码无需等待

To resolve: add one getchar(); 解决:添加一个getchar(); at the end of the the scanf() part of code, ie, at the end of if block. 在代码的scanf()部分的末尾,即if块的末尾。

To improve your "pause" feature use the following update: 要改善“暂停”功能,请使用以下更新:

 printf("\n\nPress ENTER to quit...");
 while( getchar() != '\n' ); // clear the input buffer after reading numbers with scanf
 getchar();  // wait for new input

EDIT: 编辑:

Taking into account the if-else of your program, move suggested while loop above: 考虑到程序的if-else ,建议将while循环中的内容移至上方:

 printf("Years for the analysis: "); 
 scanf("%u", &yrs);
 while( getchar() != '\n' ); // clear the input buffer

I ran into this issue as well, it's one of the more frustrating parts of C. I can't remember exactly what I did, but I remember that I ended up writing a small library to handle each type of input, ie, string, number, etc. 我也遇到了这个问题,它是C语言中最令人沮丧的部分之一。我记不清我到底做了什么,但是我记得我最终写了一个小库来处理每种类型的输入,即字符串,号码等

IIRC, I just used getline() and parsed the string into the type that I needed using atoi() and the other conversion functions found in ctype.h; IIRC,我只是使用getline()并使用atoi()和ctype.h中的其他转换函数将字符串解析为所需的类型。 I checked the length of the string and if it was 1(?) the only way that happens is if there was a new line already in the buffer, so I just called getline() again. 我检查了字符串的长度,如果它是1(?),则发生的唯一方法是缓冲区中是否已有新行,因此我再次调用了getline()。

In this way, I could write the input validation ONCE, and use it a million times. 这样,我可以编写输入验证一次,并使用一百万次。 So my code ended up looking like: 所以我的代码最终看起来像:

do {
      get_int("Enter an integer:", &myInt);//returns -123456789 for invalid input, or such
 } while ( myInt <= 0 )//assuming you only wanted positive input 

This also has the non-trivial benefit of not seeing your program crash when you entered a string and scanf() is expecting an integer. 这还有一个很重要的好处,当您输入一个字符串并且scanf()需要一个整数时,不会看到程序崩溃。

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

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