我想知道什么是最简单的方法来将int转换为C++风格的字符串和从C++风格的字符串转换为int。从字符串转换为整数
编辑
非常感谢你。当将表单字符串转换为int时,如果我传递一个char字符串会怎么样? (例如:“abce”)。
感谢&问候,
像老鼠
我想知道什么是最简单的方法来将int转换为C++风格的字符串和从C++风格的字符串转换为int。从字符串转换为整数
编辑
非常感谢你。当将表单字符串转换为int时,如果我传递一个char字符串会怎么样? (例如:“abce”)。
感谢&问候,
像老鼠
这是将字符串转换为数字。
#include "stdafx.h"
#include <iostream>
#include <string>
#include <sstream>
int convert_string_to_number(const std::string& st)
{
std::istringstream stringinfo(st);
int num = 0;
stringinfo >> num;
return num;
}
int main()
{
int number = 0;
std::string number_as_string("425");
number = convert_string_to_number(number_as_string);
std::cout << "The number is " << number << std::endl;
std::cout << "Number of digits are " << number_as_string.length() << std::endl;
}
与明智一样,以下是将数字转换为字符串。
#include "stdafx.h"
#include <iostream>
#include <string>
#include <sstream>
std::string convert_number_to_string(const int& number_to_convert)
{
std::ostringstream os;
os << number_to_convert;
return (os.str());
}
int main()
{
int number = 425;
std::string stringafterconversion;
stringafterconversion = convert_number_to_string(number);
std::cout << "After conversion " << stringafterconversion << std::endl;
std::cout << "Number of digits are " << stringafterconversion.length() << std::endl;
}
也许最简单是使用operator<<
和operator>>
用stringstream
(你可以从string
初始化stringstream
,并使用流的.str()
成员检索字符串
Boost有lexical_cast
,这使得这特别容易(t几乎没有效率的典范)。正常使用将类似int x = lexical_cast<int>(your_string);
但非常可读的(和良好命名):-) PS:指lexical_cast的 – 2010-08-24 05:16:09
使用atoi
将字符串转换为int。使用stringstream
转换另一种方式。
如果你想在订单上的东西'atoi',至少使用'strtol',它至少可以表明出现错误的时间。 – 2010-08-24 02:05:42
您可以将“%x”说明符更改为“%d”或sprintf支持的任何其他格式。确保适当地调整缓存大小“BUF”
int main(){
char buf[sizeof(int)*2 + 1];
int x = 0x12345678;
sprintf(buf, "%x", x);
string str(buf);
int y = atoi(str.c_str());
}
编辑2:
int main(){
char buf[sizeof(int)*2 + 1];
int x = 42;
sprintf(buf, "%x", x);
string str(buf);
//int y = atoi(str.c_str());
int y = static_cast<int>(strtol(str.c_str(), NULL, 16));
}
Ick ...'#include“stdafx.h”'?你需要其他三个,但你绝对可以不使用'stdafx.h'。哦,'main'应该返回一个整数。 – 2010-08-24 02:34:48
@D。 Shawley:C++实际上有一条规则,说'main'是一个特殊情况,可能会忽略'return 0;',从而产生与放在那里一样的效果。 – 2010-08-24 03:07:01
如果我调用这样的第一个函数会发生什么:'convert_string_to_number(“blah”)'?事实上,这会悄然失败,并返回相同的结果,就像我调用'convert_string_to_number(“0”)'一样。这是我的一个明确的'-1'。 – sbi 2010-08-24 08:17:17