假设你有一个字符串:
std::string s = "ABCD\t1234";
我可以使用 std::string::find
获取 '\t' 字符的偏移量,但据我所知,没有具有以下签名的函数:
int atoi_n(char *, int len);
我错过了什么吗? strtok
将 \t
替换为 \0
,我不想触及原始缓冲区。我很难相信没有 atoi
、atof
等采用长度参数的实例,但我找不到任何东西。
有人知道我是否遗漏了什么吗?我知道 boost 有一些分词器,但我想避免添加对 boost 的依赖。
看了到目前为止的评论,我想澄清一下。让我们改变一下场景: 字符缓冲区[1024]; 字符 *pStartPos; 字符 *pEndPost; pStartPos = 缓冲区 + 5; pEndPos = 缓冲区 + 10;
我们还假设您不能对 pStartPos 和 pEndPos 之外的内存做出任何假设。如何将 pStartPos 和 pEndPos 之间的字符转换为 int 而无需添加 '\0' 来缓冲或使用 substr 进行复制?
最佳答案
如果你只想解析字符串的结尾(从\t
之后的字符到最后)你只需要传递一个指向第一个字符的指针来解析到atoi
...
int n = atoi(s.c_str()+s.find('\t')+1);
(为简洁起见省略了错误检查 - 特别是,我们始终假设 \t
实际存在)
相反,如果您想从字符串的开头解析到 \t
,您可以这样做
int n = atoi(s.c_str());
因为 atoi
无论如何都会在第一个非数字字符处停止。
顺便说一句,您应该考虑使用更强大的解决方案来解析数字,例如 strtol
、sscanf
或 C++ 流 - 它们都可以报告解析错误某种方式,而 atoi
只返回 0
(这与解析字符串产生的 0 没有区别)。
顺便说一句,atoi
无论如何都不在“STL”中——它只是 C 标准库的一部分。
I know that atoi is not in the STL. I was wondering if there was anything in STL like it where you can specify the last character which you want to include in the conversion. Basically I have a buffer which may be partially filled with garbage. I know the start of possible valid data and the end of possible valid data. I don't want to depend on whitespace to end the conversion, I want to be explicit about the length of the "field" because it also may not be /0 terminated.
如果您确定垃圾不是以数字开头,您可以按原样使用 atoi
/strtol
/istringstream
- 它们会自动当他们看到垃圾时才停下来。否则,使用 substr
方法提取您需要的确切子字符串:
std::string mayContainGarbage="alcak123456amaclmò";
std::string onlyTheDigits=mayContainGarbage.substr(5, 6);
// now parse onlyTheDigits as you prefer
关于c++ - STL 中是否有进行字符串转换但带有长度参数的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17605213/