在 C 中,当我使用:
int x = 0;
char str[] = " \t123abc";
x = atoi(str);
printf("%d\n", str); //123
Run Code Online (Sandbox Code Playgroud)
123被打印。我想知道是否有一个“严格”的 C 函数,如果字符串不完全是整数,它会返回 0。(我不关心数字符号(总是正数)和基数(总是 10))。
一些例子:
" \t123abc" -> 0
" 123abc" -> 0
"123abc" -> 0
" 123 " -> 0
"123" -> 123
"123\n" -> 0
Run Code Online (Sandbox Code Playgroud)
目前我创建了一个int sstoi (char *str)函数来做到这一点:
static const unsigned int pow10[10] = {1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000};
int sstoi (char *str) {
int result = 0, length = strlen(str);
char c;
if (length > 10) return 0;
for (int i = 0; i < length; i++) {
c = str[i];
if (c < 48 || c > 57) return 0;
result += (c-48)*pow10[length-i-1];
}
return result;
}
Run Code Online (Sandbox Code Playgroud)
我认为应该改进:有人可以帮助我吗?
您可以首先检查字符串中的所有字符是否都是数字,然后使用 atoi:
if(strspn(str, "0123456789") == strlen(str))
{
x = atoi(str);
}
else
{
x = 0;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
150 次 |
| 最近记录: |