我有一个函数,检查输入是否与d1,d7,d65,等类似,这意味着它以"d“开头,然后有一个数字。
我想检查一下它是否是结构,然后在d之后返回数字。
最有效的方法是什么?它能否仅使用scanf完成?
发布于 2016-07-29 12:55:25
您可以使用sscanf并检查返回值,如果它返回1,则一个整数已被成功读取(通过%d) --这与您需要的格式相匹配;否则t没有所需的格式。
int read_fmt( char t[], int *n )
{
return sscanf( t, "d%d", n );
}
int main ()
{
char t[] = "d8787";
int n = 0;
if( read_fmt( t, &n ) == 1 )
{
printf( "correct format, n = %d\n", n );
}
else
{
perror( "incorrect format\n" );
}
}发布于 2016-07-29 13:03:10
因为这个结构很简单,所以一些简单的检查和strol应该能做到这一点,比如:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
const char* input = "d1,d7,d65,d171";
bool error = false;
const char* ptr = input;
while (*ptr != '\0')
{
// not starting with d so break with failure
if (*ptr != 'd') { error = true; break; }
// we must find a sequence of "number,..." or "number\0"
else
{
// not any character available, break with failure
if (++ptr == '\0') { error = true; break; }
else
{
int v = strtol(ptr, &ptr, 10);
// add error check for strtol
printf("found: %d\n", v);
// skip comma
if (*ptr && *ptr == ',') ++ptr;
}
}
}
printf("error = %d\n", error);但你必须处理所有的边缘案件,以确保适当的行为。
https://stackoverflow.com/questions/38659353
复制相似问题