[英]c++ Converting a std::string to int, double, etc WITHOUT using a char array
In C++ I have only seen this done by converting the string object into an array of characters. 在C ++中,我仅通过将字符串对象转换为字符数组来完成此操作。 The tutorials with an array are a bit hard for me to understand. 带数组的教程让我很难理解。 But I want to do the conversion without the array. 但是我想在没有数组的情况下进行转换。
I do have an idea how to do it: the string is "1234". 我确实有一个主意:字符串是“ 1234”。 After that I convert this text to an integer this way: 之后,我将这种文本转换为整数:
if (symol4 == "4") int_var += 4 * 1;
if (symol3 == "3") int_var += 3 * 10;
if (symol3 == "2") int_var += 2 * 100;
if (symol3 == "1") int_var += 1 * 1000; //Don't worry, I'm familiar with cycles, this code is only for explaining my algorithm
I hope you can understand the idea. 希望您能理解这个想法。
But I don't know if this is the best way. 但是我不知道这是否是最好的方法。 I don't know if there is a library that has a function that allows me to do that (I won't be surprised if there is one). 我不知道是否有一个库具有允许我执行此操作的功能(如果有的话,我不会感到惊讶)。
I don't know if not using a char array is a good idea. 我不知道不使用char数组是否是个好主意。 But that's a different question that I'm going to ask later. 但这是另一个问题,我稍后再问。
What's the best way to convert a string to an integer, double, etc WITHOUT using an array of characters. 没有使用字符数组将字符串转换为整数,双精度数等的最佳方法是什么。
boost::lexical_cast
to the rescue: int result = boost::lexical_cast<int>(input)
boost::lexical_cast
进行救援: int result = boost::lexical_cast<int>(input)
If you don't want to rely on boost, you can use a stringstream, something like: 如果您不想依靠boost,可以使用字符串流,例如:
std::stringstream ss;
int result;
ss << input;
ss >> result;
but that's rather roundabout imo 但这是一个回旋的imo
And no don't use atoi
- that function was flawed even back in C and it hasn't gotten better with time. 而且不要不使用atoi
该函数甚至在C语言中就存在缺陷,并且随着时间的推移并没有变好。 It returns 0 when an error happened while parsing - which has the obvious problem how you distinguish an error from parsing the string "0"
. 当解析时发生错误时,它返回0-这显然存在一个问题,即如何从解析字符串"0"
来区分错误。
I really can't get what your pasted code is about, but in C++ the best way to convert string to integer or float is to use stringstream
. 我确实无法获得您粘贴的代码的含义,但是在C ++中,将字符串转换为整数或浮点数的最佳方法是使用stringstream
。
const char* str = "10 20.5";
std::stringstream ss(str);
int x;
float y;
ss >> x >> y;
There is a function atoi which you can use. 您可以使用一个函数atoi 。 This converts it to a character array, but you don't have to do the math involved with indexing the array in a for loop. 这会将其转换为字符数组,但是您不必执行在for循环中索引数组的数学运算。
#include <stdlib.h>
...
String number = "1234";
int value = atoi(number.c_str());
std::cout << number;
...
For the atoi nay sayers, hopefully he'll understand this >.> 对于不喜欢说的人,希望他会明白这一点>。>
#include <boost/lexical_cast.hpp>
try {
int x = boost::lexical_cast<int>( "123" );
} catch( boost::bad_lexical_cast const& ) {
std::cout << "Error: input string was not valid" << std::endl;
}
The best way is the most efficient way, I don't think you'll find a better alternative to this, or using a character array. 最好的方法是最有效的方法,我认为您不会找到更好的替代方法,或者使用字符数组。
The standard string class already has a member function that gives you access to the internal character array, c_str(), so you can just pass this to one of the standard C library functions that parse integers, such as strtol(): 标准字符串类已经具有一个成员函数,该成员函数可让您访问内部字符数组c_str(),因此您可以将其传递给解析整数的标准C库函数之一,例如strtol():
string s = "1234";
long n = strtol(s.c_str(), 0, 10);
That's the simplest code if you already know the string is a valid integer and don't care about error checking. 如果您已经知道字符串是一个有效的整数并且不关心错误检查,那么这就是最简单的代码。 If you want full error checking you would do something like this: 如果要进行全面的错误检查,可以执行以下操作:
char* end = 0;
errno = 0;
long n = strtol(s.c_str(), &end, 10);
if (end == 0 || *end == 0)
throw invalid_argument("Not a number");
else if (errno == ERANGE)
throw overflow_error("Number is out of range");
else if (errno != 0)
throw invalid_argument("Not a number");
Alternatively you could use C++ streams if you want to avoid C style character arrays completely (or rather, hide them completely inside the classes): 另外,如果您想完全避免使用C样式字符数组(或者将它们完全隐藏在类中),则可以使用C ++流:
istringstream in(s);
int n;
in >> n;
You could also use boost::lexical_cast, which does basically the same thing. 您还可以使用boost :: lexical_cast,它的作用基本上相同。
I recommend Boost.Lexical_Cast 我推荐Boost.Lexical_Cast
Or see the upcoming Boost.Conversion 或查看即将推出的Boost.Conversion
Can also be achieved using Boost.Spirit, but is somewhat more complex 也可以使用Boost.Spirit实现,但要复杂一些
See "The String Formatters of Manor Farm" article by Herb Sutter. 请参阅Herb Sutter 撰写的“庄园农场的字符串格式化程序”。
您可能需要查看atoi函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.