SCANF 格式说明符仅读取数字
scanf format specifier to only read a number
假设我的输入值是:
"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" ) );
}
相关文章:
- 如何从保存在 Java 中C++的字节数组中读取数字?
- 从文本文件中的每一行读取数字,并计算数字重复的次数
- 如何从文件中读取数字并在数组中使用它们?
- 使用模板化函数从CSV文件中读取数字
- 根据数字在 c++ 中作为矩阵的位置从文件中读取数字
- 如何从文件中读取数字序列?
- 如何允许我的程序成功读取数字包含的文件
- 如何仅从C 中的文本文件中读取数字
- 从没有分隔符 C++ 的文件读取数字出现次数
- 读取数字并转换为单词
- 从文件,特定行中仅读取数字
- 从TextFile中读取数字,并检查它们是否在范围内
- C 从文本文件中读取数字,忽略注释
- 从文件读取数字列表到动态数组
- 我正在尝试从文件中读取数字
- 从txt文件中读取数字,添加一些数字,然后在c ++中将其重写为其他文件
- C++如何从文件中读取数字并将其分配到数组中的相应位置
- 读取数字的文本文件,并存储在C++的整数数组中
- 从文件中读取数字
- 从文本中读取数字并输出平均值