假设我的输入值是:
"2a", "6", "-20" "+20"
我想将以下值读入整数:
0, 6, -20, 20
我目前正在使用这行代码:
sscanf(input, "%d", &some_integer);
但它将"2a"读作整数值为 2 - 如何将"2a"读作 0?
但是你可以这样做
#include <stdlib.h>
#include <stdio.h>
int
main()
{
char text[100];
int value;
int count;
char *endptr;
char source[] = "2a 6 -20 +20";
char *input;
input = source;
while (sscanf(input, "%99s%n", text, &count) == 1)
{
value = strtol(text, &endptr, 10);
if (*endptr != ' ')
value = 0;
input += count;
printf("%d ", value);
}
printf("n");
return 0;
}
- 使用
sscanf()
和"%n"
说明符了解读取的字符数,并推进指针以继续阅读。 - 使用
strtol()
将读取值转换为整数,当找到第一个不可转换的字符时,转换停止,请注意,base
参数非常重要2A
因为 是一个有效的十六进制数。 - 检查转换是否成功,如果转换的所有字符都满足
*endptr == ' '
。 - 将指针前进到源字符串,并继续,直到没有更多字符可供读取。
如果您只需要检查输入字符串是否为数字,那么您应该使用以下内容
int isdecimal(const char *const text)
{
char *endptr;
if (input == NULL)
return 0;
/* the 10 is to indicate that the number is in decimal representation */
strtol(text, &endptr, 10);
return (*endptr == ' ')
}
如果您只想在不可转换时0
值,那么这就足够了
int convert(const char *const input)
{
int value;
char *endptr;
value = strtol(input, &endptr, 10);
if (*endptr != ' ')
value = 0;
return value;
}
或者
你可以这样做。%n
转换说明符指示之前的任何转换消耗了多少个字符。在您的情况下,它应该是整个字符串。
int convert( char *input )
{
int some_integer, n;
if ( sscanf( input, "%d%n", &some_integer, &n ) != 1 )
{
printf( "not a number (1)n" );
return 0;
}
if ( n != strlen(input) )
{
printf( "not a number (2)n" );
return 0;
}
return some_integer;
}
int main( void )
{
printf( "%dn", convert( "2a" ) );
printf( "%dn", convert( "+20" ) );
}