检查数组中的所有字符是否都是整数

时间:2017-09-27 23:36:47

标签: c arrays user-input

我正在使用Visual Studio 2017中的第一个简单C程序。目标是获得两个必须为整数的用户输入。

我浏览数组并检查每个字符是否都是整数但它仍然返回"输入不是有效数字"。在重试3次后,控制台崩溃了。

" projectExample.exe已触发断点。发生"是显示的消息。

int main()
{
    char userInputM[10];
    char userInputN[10];

    //get the value of M from the user
    printf("Enter a value for M: ");
    fgets(userInputM, sizeof(userInputM), stdin);
    //printf(userInputM);

    //check that the entered value for M is a valid positive number
    const int lenOfInput1 = strlen(userInputM);
    for (int i = 0; lenOfInput1; i++) {

        if (!isdigit(userInputM[i])) {
            printf("The input is not a valid number. Try again");

            printf("Enter a value for M: ");
            fgets(userInputM, sizeof(userInputM), stdin);
            printf(userInputM);
        }
    }

    //check that the entered value for N is a number 

    //convert the user input for M to an int for calculation
    //int factorM = atoi(userInputM);
    //printf("%d", factorM);

    //int result = calculate();
    //int a;
    //scanf("%d", &a);
}

2 个答案:

答案 0 :(得分:0)

如果您需要确保该数字是整数,您可以在输入中将int读入scanf()并检查返回值。

int M, rv=-1;
while(rv!=1)
{
    if(rv==0)
    {
        getchar();
    }
    rv=scanf("%d", &M);
}

scanf()会返回已成功分配值的变量数,如果上述1成功,则返回scanf()

如果输入不是数字,因此scanf()返回0,则输入的值(不是数字)在输入缓冲区中仍然未被消耗,需要消耗。可以使用getchar()来完成。 否则,scanf()将继续尝试读取相同的值,rv每次都会0

这样,您不需要字符串缓冲区或需要使用atoi()

看看here

正如评论中所指出的,fgets()会在尾随的新行(\n)中读入字符串,\n不是数字。

您可以将\n替换为\0

str[strlen(str)-1]='\0';

答案 1 :(得分:0)

int count = 0;
int i = 0;
while (userInputM[i])
{
    if (userInputM[i] >= '0' && userInputM[i] <= '9') //if it's an integer
     {
        ++count;  //do something like creating new array and put the
                  //data inside or in my case I count the # of ints
        ++i;
      }    
    else
        ++i;
}
相关问题