每次输入单词时,单词中的字母数量都会在c

时间:2015-09-25 14:18:52

标签: c

稍微混淆了从哪里开始解决这个问题。例如,如果我运行该程序并且当它要求输入正数时,我会输入" kobe",错误消息将显示4次,"我很抱歉... "等等。

 #include<stdio.h>

 int main(int agrc, char * argv[]) {
      int sum = 0, num, c;
      printf("Please enter a positive integer: \n");
      scanf_s("%d", &num);
      scanf_s("%c", &c);

      do  
      {  
           sum = num;
           if (num <= 0) {
               printf("I'm sorry, you must enter an integer greater than zero: \n");
               scanf_s("%d", &num);
               scanf_s("%c", &c);
          }

    } while (num <= 0);

    printf("The positive integer was: %d\n", sum);

    return 0;
}

2 个答案:

答案 0 :(得分:1)

检查scanf_s的返回值以确保输入操作实际成功(即用户输入十进制整数):

num = 0;
while ( num <= 0 )
{
  printf("Please enter a positive integer: \n");
  if ( scanf_s( "%d", &num ) == 0 )
  {
    /**
     * A return value of 0 means the user typed in something
     * that isn't a decimal integer; clear out the input
     * stream and try again.
     */
    while ( getchar() != '\n' )
      ; // empty loop
  }
}

答案 1 :(得分:1)

您的代码中存在多处错误,例如为什么%c和整数c?它们似乎没有任何用途或需要。您收到多条错误消息,因为scanf默认情况下%d不会“吃掉”任何非数字字符。

我个人会写这样的代码......

#include <stdio.h>
#include <string.h>

int *
int_prompt (char *message, int *number)
{
    printf (message);
    scanf ("%d", number);

    while (1) {
        if (getchar () == '\n') {
            break;
        }
    };

    return number;
}

int
main (void)
{
    int num = 0;
    int sum = 0;

    int_prompt ("Please enter a positive integer: ", &num);
    sum = num;

    while (sum <= 0) {
        int_prompt ("I'm sorry, you must enter a positive integer: ", &num);
        sum = num;
    }

    printf ("The positive integer was: %d\n", sum);

    return 0;
}

这假设您打算使用sum执行某些操作,否则您也可以取消它。

如果您愿意,请将scanf替换为scanf_s