将字符串的子部分转换为 int C++

convert subsection of a string to int c++

本文关键字:转换 int C++ 字符串      更新时间:2023-10-16

我有一个看起来像下面的字符串:

水平分档:4

我将整行存储为字符串,并且可以使用类似 linestring[30] 的东西访问数字 4,其中 linestring 是整行存储的字符串。我正在尝试将数字 4 作为整数而不是字符串访问。我该怎么做?我尝试使用 atoi(linestring[30].c_str(((;但这不喜欢对线串有一个参数。我无法使用外部库,例如 boost 等。我该怎么做?

使用 substr 而不是 operator[] 。它会给你另一个std::string,而不是一个char。然后使用 std::stoi 将字符串转换为整数。

或者,使用从operator[]返回的char创建一个要应用std::stoi的新std::string

在 C++11 之前,使用 std::istringstream 而不是 std::stoi

顺便说一句,远离atoi.如果"0"应该是有效的输入,则无法进行错误检查。

对于更通用的方法,您有以下形式的对:

foo: <number>

你可以使用这样的东西:

std::string s = "Horizontal Binning: 4";
size_t pos = s.find_last_of(':');
if(pos != std::string::npos)
{
    int num;
    std::stringstream(s.erase(0, pos + 1)) >> num;
    std::cout << "num = " << num << std::endl;
}
else // give error here
您可以使用

int value = atoi(linestring.c_str() + 30);

但您必须确保字符串至少为 30 个字符,否则这将意味着未定义的行为。

如果您不知道数字前面的文本有多长,您可以简单地循环,直到找到一个数字并从那里调用 atoi:

auto it = begin(str);
while (it != end(str) && !isdigit(*it))
    ++it;
cout << atoi(&*it) << endl;

由于这是C++并且您正在使用std::string,请使用stoi而不是atoi。这是一个受无辜旁观者答案启发的通用解决方案。

要找到字符串中:的位置并在此之后解析 int:

size_t start = linestring.find_last_of(':') + 1;
int i = std::stoi(linestring.substr(start));

你甚至可以把它变成一行字。


或者,如果您知道数字将始终只有一个数字,并且它是字符串中的最后一个字符:

int i = linestring.back() - '0';

另一个选项是尝试匹配模式的sscanf

#include <cstdio>
#include <string>
void Extract(const std::string& s) {
    int value = 0;
    int r = sscanf(s.c_str(), "Horizontal Binning: %d", &value);
    if (r == 1) {
        printf("value is %dn", value);
    } else {
        printf("cannot extract valuen");
    }
}
int main() {
    Extract("Horizontal Binning: 4");
    Extract("Whatever: 4");
}

输出为:

value is 4
cannot extract value