将字符串的子部分转换为 int C++
convert subsection of a string to int c++
我有一个看起来像下面的字符串:
水平分档: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
相关文章:
- 从"int*"强制转换为"unsigned int"会丢失精度错误
- 是否可以从int转换为enum类类型
- 如何在C++中将一个无符号的 int 转换为两个无符号的短裤?
- 功能样式转换从 'int' 到 'ItemType' 的匹配转换
- 将 int 数组转换为 std::vector<int*>
- 如何转换 int 变量并附加到常量 wchar_t*
- 类型转换<int>的舍入问题
- 在Objective-C中调用sqlite3数据库时,如何调用和转换int/NSNumber
- 转换 int -> 无符号长 长 是否由标准定义
- 简单的 int 到字符串转换..int to const char* 无效
- 如何将转换 int 除法键入为浮点数
- C++类型转换 int * 到类
- 预期的类型说明符,并且无法在初始化时转换“int*”
- 转换int并将其与char*连接
- 字符串流在转换int型时添加新行
- 转换int为字符串/char c++ /Arduino
- c# P-Invoke:如何转换INT fun(BYTE *bStream, UINT16 *nCount, const
- 类型转换(int**)和int(*)的区别
- 从"int"到"nodeType"的无效转换<int>
- 从无符号int构造对强制转换int的引用