[英]Extracting integers from strings without sstream c++
What is the simplest way to extract the following integers from a string such as: "54 232 65 12". 从字符串中提取以下整数的最简单方法是什么,例如:“54 232 65 12”。
And what if the last number is a long long int. 如果最后一个数字是一个很长的int,该怎么办? Is it possible to do this without sstream
没有sstream就可以做到这一点
Try this: 试试这个:
#include <cstdlib>
#include <cstdio>
#include <cerrno>
#include <cstring>
int main()
{
char str[] = " 2 365 2344 1234444444444444444444567 43";
for (char * e = str; *e != '\0'; )
{
errno = 0;
char const * s = e;
unsigned long int n = strtoul(s, &e, 0);
if (errno) // conversion error (e.g. overflow)
{
std::printf("Error (%s) encountered converting:%.*s.\n",
std::strerror(errno), e - s, s);
continue;
}
if (e == s) { ++e; continue; } // skip inconvertible chars
s = e;
printf("We read: %lu\n", n);
}
}
In C++11 you can also use std::strtoull
, which returns an unsigned long long int
. 在C ++ 11中,您还可以使用
std::strtoull
,它返回一个unsigned long long int
。
( Live example .) ( 实例 。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.