C:多个 scanf,当我输入一个 scanf 的值时,它会跳过第二个 scanf [英] C: Multiple scanf's, when I enter in a value for one scanf it skips the second scanf

查看:51
本文介绍了C:多个 scanf,当我输入一个 scanf 的值时,它会跳过第二个 scanf的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个代码块(函数被省略,因为逻辑是家庭作业的一部分):

I have this block of code (functions omitted as the logic is part of a homework assignment):

#include <stdio.h>

int main()
{
    char c = 'q';
    int size; 

    printf("
Shape (l/s/t):");
    scanf("%c",&c);

    printf("Length:"); 
    scanf("%d",&size);

    while(c!='q')
    {
        switch(c)
        {
            case 'l': line(size); break; 
            case 's': square(size); break;
            case 't': triangle(size); break; 
        }


        printf("
Shape (l/s/t):");
        scanf("%c",&c);

        printf("
Length:"); 
        scanf("%d",&size);
    }

    return 0; 
}

前两个 Scanf 工作得很好,一旦我们进入 while 循环就没问题了,我有一个问题,当你应该被提示输入一个新的形状字符时,​​它反而跳到 printf of Length 并等待从那里获取字符的输入,然后在循环的下一次迭代中输入小数.

The first two Scanf's work great, no problem once we get into the while loop, I have a problem where, when you are supposed to be prompted to enter a new shape char, it instead jumps down to the printf of Length and waits to take input from there for a char, then later a decimal on the next iteration of the loop.

预循环迭代:

Scanf:形状.效果很好
Scanf:长度.没问题

Scanf: Shape. Works Great
Scanf: Length. No Problem

循环 1.

Scanf:形状.跳过这个
Scanf:长度.问题,这个 scanf 映射到形状字符.

Scanf: Shape. Skips over this
Scanf: length. Problem, this scanf maps to the shape char.

循环2
Scanf:形状.跳过这个
Scanf:长度.问题,这个 scanf 现在映射到大小 int.

Loop 2
Scanf: Shape. Skips over this
Scanf: length. Problem, this scanf maps to the size int now.

为什么要这样做?

推荐答案

scanf("%c")ENTER 键读取换行符.

scanf("%c") reads the newline character from the ENTER key.

当你输入 15 时,你输入一个 1,一个 5,然后按 ENTER钥匙.所以现在输入缓冲区中有三个字符.scanf("%d") 读取 15,将它们解释为数字 15,但是换行符仍在输入缓冲区中.scanf("%c") 会立即读取这个换行符,然后程序会继续下一个 scanf("%d"),并等待你输入一个数字.

When you type let's say 15, you type a 1, a 5 and then press the ENTER key. So there are now three characters in the input buffer. scanf("%d") reads the 1 and the 5, interpreting them as the number 15, but the newline character is still in the input buffer. The scanf("%c") will immediately read this newline character, and the program will then go on to the next scanf("%d"), and wait for you to enter a number.

通常的建议是使用 fgets 读取整行输入,并在单独的步骤中解释每一行的内容.解决您当前问题的一个更简单的方法是在每个 scanf("%d") 之后添加一个 getchar().

The usual advice is to read entire lines of input with fgets, and interpret the content of each line in a separate step. A simpler solution to your immediate problem is to add a getchar() after each scanf("%d").

这篇关于C:多个 scanf,当我输入一个 scanf 的值时,它会跳过第二个 scanf的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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