同样的问题。 我的解决方案是使用get()来提取scanf()留下的内容

同样的问题。 我的解决方案是使用get()来提取scanf()留下的内容,c,gcc,scanf,C,Gcc,Scanf,这里是稍微重写的操作代码;也许对他没用,但也许这会帮助其他人 #include <stdio.h> int main() { int number, p = 0, n = 0; char unwantedCharacters[40]; //created array to catch unwanted input unwantedCharacters[0] = 0; //initialzed first byt

这里是稍微重写的操作代码;也许对他没用,但也许这会帮助其他人

#include <stdio.h>

    int main()
    {
        int number, p = 0, n = 0;
        char unwantedCharacters[40];  //created array to catch unwanted input
        unwantedCharacters[0] = 0;    //initialzed first byte of array to zero

        while (1)
        {
            printf("-> ");
            scanf("%d", &number);
            gets(unwantedCharacters);        //collect what scanf() wouldn't from the input stream
            if (unwantedCharacters[0] == 0)  //if unwantedCharacters array is empty (the user's input is valid)
            {
                if (number > 0) p++;
                else if (number < 0) n++;
                else break; /* 0 given */
            }
            else
                printf("Err...\n");
        }
        printf("Read %d positive and %d negative numbers\n", p, n);
        return 0;
    }
#包括
int main()
{
整数,p=0,n=0;
char unwantedCharacters[40];//创建数组以捕获不需要的输入
unwantedCharacters[0]=0;//已将数组的第一个字节初始化为零
而(1)
{
printf(“->”);
scanf(“%d”和编号);
获取(unwantedCharacters);//从输入流中收集scanf()不会收集的内容
if(unwantedCharacters[0]==0)//如果unwantedCharacters数组为空(用户的输入有效)
{
如果(数字>0)p++;
如果(数字<0)n++;
else中断;/*0给定*/
}
其他的
printf(“Err…\n”);
}
printf(“读取%d个正数和%d个负数\n”,p,n);
返回0;
}
尝试使用以下方法:

if (scanf("%d", &number) == 0) {
        printf("Err...\n");
        break;
    }
这对我来说很好。。。试试这个。。
continue语句不合适,因为Err..只能执行一次。所以,试试我测试的break。。。这对你很管用。。我测试了……

晚上好。我最近也遇到了同样的问题,我找到了一个可能对很多人都有帮助的解决方案。实际上,函数“scanf”在内存中留下了一个缓冲区。。。这就是产生无限循环的原因。因此,如果初始scanf包含“null”值,则实际上必须将该缓冲区“存储”到另一个变量。我的意思是:

#include <stdio.h>
int n;
char c[5];
main() {
    while (1) {
        printf("Input Number: ");
        if (scanf("%d", &n)==0) {  //if you type char scanf gets null value
            scanf("%s", &c);      //the abovementioned char stored in 'c'
            printf("That wasn't a number: %s\n", c);
        }
        else printf("The number is: %d\n", n);
    }
}
#包括
int n;
charc[5];
main(){
而(1){
printf(“输入编号:”);
如果(scanf(“%d”,&n)==0){//如果键入char,scanf将获取空值
scanf(“%s”,&c);//上述字符存储在“c”中
printf(“那不是一个数字:%s\n”,c);
}
else printf(“编号为:%d\n”,n);
}
}

输入非数字时会发生错误,且非数字仍保留在输入缓冲区中。你应该跳过它。而且,即使是这种符号组合,例如
1a
,在开始时也会被理解为数字1,我认为您也应该跳过这种输入

程序可以按以下方式运行

#include <stdio.h>
#include <ctype.h>

int main(void) 
{
    int p = 0, n = 0;

    while (1)
    {
        char c;
        int number;
        int success;

        printf("-> ");

        success = scanf("%d%c", &number, &c);

        if ( success != EOF )
        {
            success = success == 2 && isspace( ( unsigned char )c );
        }

        if ( ( success == EOF ) || ( success && number == 0 ) ) break;

        if ( !success )
        {
            scanf("%*[^ \t\n]");
            clearerr(stdin);
        }
        else if ( number > 0 )
        {
            ++p;
        }
        else if ( number < n )
        {
            ++n;
        }
    }

    printf( "\nRead %d positive and %d negative numbers\n", p, n );

    return 0;
}

为了部分解决您的问题,我只需在scanf之后添加这一行:

fgetc(stdin); /* to delete '\n' character */
下面是您的代码和行:

#include <stdio.h>

int main()
{
    int number, p = 0, n = 0;

    while (1) {
        printf("-> ");
        if (scanf("%d", &number) == 0) {
            fgetc(stdin); /* to delete '\n' character */
            printf("Err...\n");
            continue;
        }

        if (number > 0) p++;
        else if (number < 0) n++;
        else break; /* 0 given */
    }

    printf("Read %d positive and %d negative numbers\n", p, n);
    return 0;
}

解决方案:您需要添加
fflush(stdin)当从
scanf
返回
0

/* ... */
    printf("0 to quit -> ");
    fflush(stdout);
    while (fgets(buf, sizeof buf, stdin)) {
      if (sscanf(buf, "%d", &number) != 1) {
        fprintf(stderr, "Err...\n");
      } else {
        work(number);
      }
      printf("0 to quit -> ");
      fflush(stdout);
    }
/* ... */
原因:当遇到错误时,它似乎将输入字符留在缓冲区中,因此每次调用
scanf
时,它只是不断尝试处理无效字符,但从不将其从缓冲区中删除。调用
fflush
时,输入缓冲区(stdin)将被清除,因此无效字符将不再被重复处理

您的程序已修改:下面是您的程序经过必要更改后的修改

#include <stdio.h>

int main()
{
    int number, p = 0, n = 0;

    while (1) {
        printf("-> ");
        if (scanf("%d", &number) == 0) {
            fflush(stdin);
            printf("Err...\n");
            continue;
        }

        if (number > 0) p++;
        else if (number < 0) n++;
        else break; /* 0 given */
    }

    printf("Read %d positive and %d negative numbers\n", p, n);
    return 0;
}
#包括
int main()
{
整数,p=0,n=0;
而(1){
printf(“->”);
如果(scanf(“%d”,&number)==0){
fflush(stdin);
printf(“Err…\n”);
继续;
}
如果(数字>0)p++;
如果(数字<0)n++;
else中断;/*0给定*/
}
printf(“读取%d个正数和%d个负数\n”,p,n);
返回0;
}
//您只需清除缓冲区即可!
#包括
int main()
{
整数,p=0,n=0;
char clearBuf[256];//JG:
而(1){
printf(“->”);
如果(scanf(“%d”,&number)==0){
fgets(标准格式,256,clearBuf);//JG:
printf(“Err…\n”);
继续;
}
如果(数字>0)p++;
如果(数字<0)n++;
else中断;/*0给定*/
}
printf(“读取%d个正数和%d个负数\n”,p,n);
返回0;
}

“过早优化是万恶之源”。。。但是切换常量:
“\n”
EOF
:)更可能出现,你希望
EOF
能100%保证出现;否则,您要么有一个非常快的键盘,要么有一个非常慢的cputh,
中的上述复杂情况,而
语句的条件是不必要的。@ilgaar您是什么意思?我觉得很好。如果输入是“abc”,代码会打印三次“Err…”。是的,这是一个相当贫民区。我会稍微调整一下。现在如果输入是“ab-10”,它将错误地从输入中删除减号,并将“10”作为下一个数字。我知道它很旧,但只需将其更改为
,而(!isdigit(c)&&c!='-')
,这也有助于减号。这仍然会导致多行输入,请尝试
4t
t4
4t
将为您提供
->错误
t4
甚至不会给您任何错误,但仍然有多个输入行:
->->
对于像用户输入这样重要的内容,如果不在您自己的树中提供非标准扩展,您就不能依赖它们。如果你编辑你的答案来反映这一点,我将撤回我的反对票。@tinkertim:这个问题指定了Linux上的gcc,保证
strtol
是可用的。所以,至少暗示一下如何打开这种扩展可能会有所帮助:)@Andomar:我所反对的是getline()@TimPost getline()和getdelim()最初都是GNU扩展。它们在POSIX.1-2008中被标准化。在if语句之前添加这个while循环确实会导致错误的程序行为。确切地说,在第一次输入之后不会显示“->”提示,可能是正确的,也可能是错误的。您的
虽然
循环将消耗所有内容,
'\n'
包括在内。Afaik fflush()在每个系统上的工作方式不同。至少在我的Linux机器上,fflush(stdout)没有帮助
#include <stdio.h>
#include <ctype.h>
#include <string.h>

int main(int argc, const char * argv[]) {

    char line[10];
    int loop, arrayLength, number, nan;
    arrayLength = sizeof(line) / sizeof(char);
    do {
        nan = 0;
        printf("Please enter a number:\n");
        fgets(line, arrayLength, stdin);
        for(loop = 0; loop < arrayLength; loop++) { // search for any none numeric charcter inisde the line array
            if(line[loop] == '\n') { // stop the search if there is a carrage return
                break;
            }
            if((line[0] == '-' || line[0] == '+') && loop == 0) { // Exculude the sign charcters infront of numbers so the program can accept both negative and positive numbers
                continue;
            }
            if(!isdigit(line[loop])) { // if there is a none numeric character then add one to nan and break the loop
                nan++;
                break;
            }
        }
    } while(nan || strlen(line) == 1); // check if there is any NaN or the user has just hit enter
    sscanf(line, "%d", &number);
    printf("You enterd number %d\n", number);
    return 0;
}
#include <stdio.h>

    int main()
    {
        int number, p = 0, n = 0;
        char unwantedCharacters[40];  //created array to catch unwanted input
        unwantedCharacters[0] = 0;    //initialzed first byte of array to zero

        while (1)
        {
            printf("-> ");
            scanf("%d", &number);
            gets(unwantedCharacters);        //collect what scanf() wouldn't from the input stream
            if (unwantedCharacters[0] == 0)  //if unwantedCharacters array is empty (the user's input is valid)
            {
                if (number > 0) p++;
                else if (number < 0) n++;
                else break; /* 0 given */
            }
            else
                printf("Err...\n");
        }
        printf("Read %d positive and %d negative numbers\n", p, n);
        return 0;
    }
if (scanf("%d", &number) == 0) {
        printf("Err...\n");
        break;
    }
#include <stdio.h>
int n;
char c[5];
main() {
    while (1) {
        printf("Input Number: ");
        if (scanf("%d", &n)==0) {  //if you type char scanf gets null value
            scanf("%s", &c);      //the abovementioned char stored in 'c'
            printf("That wasn't a number: %s\n", c);
        }
        else printf("The number is: %d\n", n);
    }
}
#include <stdio.h>
#include <ctype.h>

int main(void) 
{
    int p = 0, n = 0;

    while (1)
    {
        char c;
        int number;
        int success;

        printf("-> ");

        success = scanf("%d%c", &number, &c);

        if ( success != EOF )
        {
            success = success == 2 && isspace( ( unsigned char )c );
        }

        if ( ( success == EOF ) || ( success && number == 0 ) ) break;

        if ( !success )
        {
            scanf("%*[^ \t\n]");
            clearerr(stdin);
        }
        else if ( number > 0 )
        {
            ++p;
        }
        else if ( number < n )
        {
            ++n;
        }
    }

    printf( "\nRead %d positive and %d negative numbers\n", p, n );

    return 0;
}
-> 1
-> -1
-> 2
-> -2
-> 0a
-> -0a
-> a0
-> -a0
-> 3
-> -3
-> 0

Read 3 positive and 3 negative numbers
fgetc(stdin); /* to delete '\n' character */
#include <stdio.h>

int main()
{
    int number, p = 0, n = 0;

    while (1) {
        printf("-> ");
        if (scanf("%d", &number) == 0) {
            fgetc(stdin); /* to delete '\n' character */
            printf("Err...\n");
            continue;
        }

        if (number > 0) p++;
        else if (number < 0) n++;
        else break; /* 0 given */
    }

    printf("Read %d positive and %d negative numbers\n", p, n);
    return 0;
}
int c;
while ((c = fgetc(stdin)) != '\n' && c != EOF);
#include <stdio.h>

int main()
{
    int number, p = 0, n = 0;

    while (1) {
        printf("-> ");
        if (scanf("%d", &number) == 0) {
            fflush(stdin);
            printf("Err...\n");
            continue;
        }

        if (number > 0) p++;
        else if (number < 0) n++;
        else break; /* 0 given */
    }

    printf("Read %d positive and %d negative numbers\n", p, n);
    return 0;
}
// all you need is to clear the buffer!

#include <stdio.h>

int main()
{
    int number, p = 0, n = 0;
    char clearBuf[256]; //JG:
    while (1) {
        printf("-> ");
        if (scanf("%d", &number) == 0) {
            fgets(stdin, 256, clearBuf); //JG:
            printf("Err...\n");
            continue;
        }

        if (number > 0) p++;
        else if (number < 0) n++;
        else break; /* 0 given */
    }

    printf("Read %d positive and %d negative numbers\n", p, n);
    return 0;
}