Convertion between string and int in C++

来源:互联网 发布:js 遍历array 中对象 编辑:程序博客网 时间:2024/05/17 04:50

int to string

1st way

int a = 10;char buffer[128];char *intStr = itoa(a, buffer, 10);std::string str = std::string(intStr);

itoa non-standard function

This function is not defined in ANSI-C and is not part of C++, but is supported by some compilers.

A standard-compliant alternative for some cases may be sprintf:
1. sprintf(str,"%d",value) converts to decimal base.
2. sprintf(str,"%x",value) converts to hexadecimal base.
3. sprintf(str,"%o",value) converts to octal base.

2nd way

int a = 10;std::stringstream ss;ss << a;std::string str = ss.str();

stringstream

3rd way(c++11)

std::string s = std::to_string(10);

to_string

Further Reading:
Converting numbers to strings and strings to numbers
easiest way to convert int to string in c++

string to int

1st way

string Text = "456";    // string containing the numberint Result;             //number which will contain the resultistringstream convert(Text); // stringstream used for the conversion constructed with the contents of 'Text'                              // ie: the stream will start containing the characters of 'Text'if ( !(convert >> Result) ) //give the value to 'Result' using the characters in the stream    Result = 0;             //if that fails set 'Result' to 0//'Result' now equal to 456 

This conversion is even easier to reduce to a single line:

string Text = "456";int Number;if ( ! (istringstream(Text) >> Number) ) Number = 0

2nd way(c++11)

text = "456"number = stoi(number);

stoi

Converting numbers to strings and strings to numbers

vector<int> to string

Discription:

// inputvector<int>{1,3,4};// after vector<int> to string// outputstring s = {"134"};
#include <algorithm>#include <iostream>#include <string>int main(){    std::vector<int> v = { 1,3,2,7 };    std::string res(v.size(), 0);    std::transform(v.begin(), v.end(), res.begin(),        [](int k) { return static_cast<char>(k+'0'); });    std::cout << res << '\n';    return 0;}

transform

阅读全文
0 0
原创粉丝点击