2010-08-24 66 views
2

我想知道什么是最简单的方法来将int转换为C++风格的字符串和从C++风格的字符串转换为int。从字符串转换为整数

编辑

非常感谢你。当将表单字符串转换为int时,如果我传递一个char字符串会怎么样? (例如:“abce”)。

感谢&问候,

像老鼠

回答

0

这是将字符串转换为数字。

#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; 
} 
+1

Ick ...'#include“stdafx.h”'?你需要其他三个,但你绝对可以不使用'stdafx.h'。哦,'main'应该返回一个整数。 – 2010-08-24 02:34:48

+1

@D。 Shawley:C++实际上有一条规则,说'main'是一个特殊情况,可能会忽略'return 0;',从而产生与放在那里一样的效果。 – 2010-08-24 03:07:01

+0

如果我调用这样的第一个函数会发生什么:'convert_string_to_number(“blah”)'?事实上,这会悄然失败,并返回相同的结果,就像我调用'convert_string_to_number(“0”)'一样。这是我的一个明确的'-1'。 – sbi 2010-08-24 08:17:17

3

也许最简单是使用operator<<operator>>stringstream(你可以从string初始化stringstream,并使用流的.str()成员检索字符串

Boost有lexical_cast,这使得这特别容易(t几乎没有效率的典范)。正常使用将类似int x = lexical_cast<int>(your_string);

+0

但非常可读的(和良好命名):-) PS:指lexical_cast的 – 2010-08-24 05:16:09

-1

使用atoi将字符串转换为int。使用stringstream转换另一种方式。

+5

如果你想在订单上的东西'atoi',至少使用'strtol',它至少可以表明出现错误的时间。 – 2010-08-24 02:05:42

1

您可以将“%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)); 
} 
+0

为什么sizeof(int)* 2? – mousey 2010-08-24 02:17:52

+0

假设整数为4个字节,则会有8个十六进制数字和“%x”说明符。 – Chubsdad 2010-08-24 02:20:18

+0

我在这里错过了什么吗? 'sprintf(buf,“%x”,42);'将'2a“放入'buf'中。 'atoi(“2a”)'将返回'2'而不是'42'。 – 2010-08-24 02:32:59