仅获取C/C+中的简单数字+;
我有一个函数仅获取C/C+中的简单数字+;,c,stdio,C,Stdio,我有一个函数stoi如下: static int *stoi(const char *c) { int *r = new int[2]; r[1] = sscanf(c, "%d", &r[0]); return r; } 例如,当我给出c=“a5”时,它不起作用 当我给出c=“543336535”时,它就起作用了 但是当我给出c=“45sdfff sdbsdf esg5sq4f”时,它将返回r[0]=45,我不希望这样,因为45后面有一些非数字字符 我只希望我
stoi
如下:
static int *stoi(const char *c) {
int *r = new int[2];
r[1] = sscanf(c, "%d", &r[0]);
return r;
}
例如,当我给出c=“a5”
时,它不起作用
当我给出c=“543336535”
时,它就起作用了
但是当我给出c=“45sdfff sdbsdf esg5sq4f”
时,它将返回r[0]=45
,我不希望这样,因为45
后面有一些非数字字符
我只希望我的函数读取一个纯数字字符串。要对已有的代码进行最小更改,可以使用
%n
sscanf的功能:
int chars_read;
r[1] = sscanf(c, "%d%n", &r[0], &chars_read);
如果chars\u read
小于字符串的长度,则sscanf
不会使用所有字符,因此字符串不完全由单个整数组成
指出引入的附加示例与标准相矛盾,但同时,对标准进行了更新以解决冲突。以下是您在面对sscanf
实现的不确定行为时如何解释结果:
switch (r[1]) {
case EOF: // empty string
break;
case 0: // doesn't start with numeric characters
break;
case 1: // starts with number; sscanf follows standards
case 2: // starts with number; sscanf follows TC1
if (c[chars_read] == '\0')
r[1] = 1; // we read entire string
else
r[1] = 0; // didn't read entire string; pretend we read nothing
break;
default: // shouldn't happen
assert(FALSE);
}
如果您使用的是C,那么您可以使用strtol
来执行您可能称之为临时转换的操作。它将为您提供一个指向它可以转换的数据结尾的指针。如果这不是字符串的结尾,那么至少在它可以转换的内容后面有一些垃圾
如果使用C++,则可能需要使用Booost < Cord> ListalyCase选择一种语言——C或C++ +任何人,如果C可能,C,C++,.Cux>新INT[2 ] < /C>是C++中的一种差的风格,使用
std::array
或std::vector
@Quent42340:当然可以在C中使用;-]警告不要将scanf的返回值与%n
格式一起使用。最好设置r[1]=(chars\u read==strlen(c))
。谢谢你,戴夫。我想我的修订现在涵盖了所有内容。如果没有,请编辑。