gpt4 book ai didi

c - 在 C/C++ 中只获取一个简单的数字

转载 作者:太空狗 更新时间:2023-10-29 15:59:17 27 4
gpt4 key购买 nike

我有一个像这样的函数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...

之后的非数字字符

我只希望我的函数读取纯数字字符串。

最佳答案

为了对您已有的代码进行最小的更改,您可以使用 sscanf%n 功能:

int chars_read;
r[1] = sscanf(c, "%d%n", &r[0], &chars_read);

如果 chars_read 小于字符串的长度,则 sscanf 没有消耗所有字符,因此字符串不完全由单个整数组成.

The Linux documentation for scanf指出 Technical Corrigendum 1 引入的附加示例与标准相矛盾,但与此同时,标准已更新以解决冲突。面对您可能遇到的 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 - 在 C/C++ 中只获取一个简单的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10640381/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com