如何在没有\ n的情况下获得角色?

时间:2010-11-02 02:40:57

标签: c

在我的代码中,我试图忽略新行。有没有更好的方法呢?

        do
        {   
            scanf("%c",&wouldCount);
        } while(wouldCount == '\n');

原始代码

#include <stdio.h>

int main()
{
    char Yes = 'Y';
    char wouldCount;
    int counter;
    int start;
    int end;
    int increment;
    const END_DEFAULT = 1;
    const INCREMENT_DEFAULT = 1;
    printf("Would you like to count?");
    scanf("%c",&wouldCount);
    while(wouldCount == 'Y' || wouldCount == 'y')
    {
        printf("Please enter start number.");
        scanf("%d",&start);
        printf("Please enter a number you would like to stop at?");
        scanf("%d",&end);
        printf("Please enter a number to increment by.");
        scanf("%d",&increment);
        if(end < start)
        {
            end = start + END_DEFAULT;
        }
        if(increment <= 0)
        {
            increment = INCREMENT_DEFAULT;
        }
        for(counter = start; counter < end; counter += increment)
        {
            printf("%d\n",counter);
        }
        printf("Would you like to count?");
        do
        {   
            scanf("%c",&wouldCount);
        } while(wouldCount == '\n');
    }
return 0;       
}

1 个答案:

答案 0 :(得分:3)

你可以改变scanf(“%c”,&amp; wouldCount); to scanf(“\ n%c”,&amp; wouldCount);以及放弃do / while循环。这将告诉scanf忽略没有输入字符的输入。

请参阅scanf c++ reference