[英]How to check input in command line is integer in C?
我希望在命令行中檢查輸入的代碼是整數。 即 10b 無效。 我試過 isdigit() 但不起作用? 提前致謝。
#include <cs50.h>
#include <stdio.h>
#include <ctype.h>
int main(int argc, string argv[])
{
if (argc == 2)
{
int key = atoi(argv[1]);
if (isdigit(key))
{
printf("Success\n\%i\n", key);
exit(0);
}
}
printf("Usage: ./caesar key\n");
return 1;
}
函數isDigit
檢查單個字符是否為數字,即在'0'..'9'
之間的范圍內。 要檢查字符串是否為數字,我建議使用函數strtol
。
long strtol(const char *str, char **str_end, int base )
將字符串str
轉換為整數,並將指針str_end
設置為不再參與轉換的第一個字符。 如果您要求數字str_end
不能有任何字符,則str_end
必須指向字符串的結尾,即字符串終止字符'\\0'
:
#include <stdio.h>
#include <stdlib.h>
int isNumber(const char* str) {
if (!str || *str=='\0') { // NULL str or empty str: not a number
return 0;
}
char* endOfNum;
strtol(str,&endOfNum,10);
if (*endOfNum == '\0') { // string is at its end; everything in it was a valid part of the number
return 1;
} else {
return 0; // something that is not part of a number followed.
}
}
int main() {
const char* vals[] = {
"10b",
"-123",
"134 ",
" 345",
"",
NULL
};
for (int i=0; vals[i]; i++) {
printf("testing '%s': %d\n", vals[i], isNumber(vals[i]));
}
}
輸出:
testing '10b': 0
testing '-123': 1
testing '134 ': 0
testing ' 345': 1
testing '': 0
根據您的需要調整特殊情況(如空字符串或 NULL 字符串)的含義。
我的第一個想法是使用類似的東西:
int inputvalue = 0;
if (sscanf(argv[i], "%d", &inputvalue) == 1)
{
// it's ok....
}
else
{
// not an integer!
}
isdigit
函數檢查單個字符是否代表單個數字。 (數字 - 0 1 2 3 4 5 6 7 8 9)。
為了檢查字符串是否為整數,您可以使用這樣的函數。 它會
bool isNumber(char number[])
{
int i = 0;
// only if you need to handle negative numbers
if (number[0] == '-')
i = 1;
for (; number[i] != 0; i++)
{
if (!isdigit(number[i]))
return false;
}
return true;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.