How to check if a string is a number?

后端 未结 10 2560
没有蜡笔的小新
没有蜡笔的小新 2020-11-29 10:03

I want to check if a string is a number with this code. I must check that all the chars in the string are integer, but the while returns always isDigit = 1. I don\'t know wh

10条回答
  •  忘掉有多难
    2020-11-29 10:31

    In this part of your code:

    if(tmp[j] > 57 && tmp[j] < 48)
      isDigit = 0;
    else
      isDigit = 1;
    

    Your if condition will always be false, resulting in isDigit always being set to 1. You are probably wanting:

    if(tmp[j] > '9' || tmp[j] < '0')
      isDigit = 0;
    else
      isDigit = 1;
    

    But. this can be simplified to:

    isDigit = isdigit(tmp[j]);
    

    However, the logic of your loop seems kind of misguided:

    int isDigit = 0;
    int j=0;
    while(j

    As tmp is not a constant, it is uncertain whether the compiler will optimize the length calculation out of each iteration.

    As @andlrc suggests in a comment, you can instead just check for digits, since the terminating NUL will fail the check anyway.

    while (isdigit(tmp[j])) ++j;
    

提交回复
热议问题