[英]Converting an int to std::string
將 int 轉換為字符串的最短方法是什么,最好是內聯的? 歡迎使用 stl 和 boost 的答案。
您可以在 C++11 中使用std::to_string
int i = 3;
std::string str = std::to_string(i);
#include <sstream>
#include <string>
const int i = 3;
std::ostringstream s;
s << i;
const std::string i_as_string(s.str());
boost::lexical_cast<std::string>(yourint)
來自boost/lexical_cast.hpp
適用於支持 std::ostream 的所有內容,但速度不如itoa
它甚至似乎比 stringstream 或 scanf 更快:
嗯,眾所周知的方法(在 C++11 之前)是使用流運算符:
#include <sstream>
std::ostringstream s;
int i;
s << i;
std::string converted(s.str());
當然,您可以使用模板函數將其概括為任何類型 ^^
#include <sstream>
template<typename T>
std::string toString(const T& value)
{
std::ostringstream oss;
oss << value;
return oss.str();
}
如果您不能使用 C++11 中的std::to_string
,您可以按照 cppreference.com 上的定義編寫它:
std::string to_string( int value )
將一個有符號十進制整數轉換為一個字符串,其內容與std::sprintf(buf, "%d", value)
為足夠大的 buf 產生的內容相同。
實施
#include <cstdio>
#include <string>
#include <cassert>
std::string to_string( int x ) {
int length = snprintf( NULL, 0, "%d", x );
assert( length >= 0 );
char* buf = new char[length + 1];
snprintf( buf, length + 1, "%d", x );
std::string str( buf );
delete[] buf;
return str;
}
你可以用它做更多的事情。 只需使用"%g"
將float或double轉換為字符串,使用"%x"
將int轉換為十六進制表示,等等。
非標准函數,但它在最常見的編譯器上實現:
int input = MY_VALUE;
char buffer[100] = {0};
int number_base = 10;
std::string output = itoa(input, buffer, number_base);
更新
C++11 引入了幾個std::to_string
重載(注意它默認為 base-10)。
下面的宏不像一次性使用的ostringstream
或boost::lexical_cast
那樣緊湊。
但是如果你需要在你的代碼中重復轉換為字符串,這個宏在使用中比每次直接處理字符串流或顯式轉換更優雅。
它也非常通用,因為它可以轉換operator<<()
支持的所有內容,甚至可以組合使用。
定義:
#include <sstream>
#define SSTR( x ) dynamic_cast< std::ostringstream & >( \
( std::ostringstream() << std::dec << x ) ).str()
說明:
std::dec
是一種無副作用的方法,可以將匿名ostringstream
轉換為通用ostream
因此operator<<()
函數查找對所有類型都能正常工作。 (否則,如果第一個參數是指針類型,則會遇到麻煩。)
dynamic_cast
將類型返回給ostringstream
因此您可以對其調用str()
。
使用:
#include <string>
int main()
{
int i = 42;
std::string s1 = SSTR( i );
int x = 23;
std::string s2 = SSTR( "i: " << i << ", x: " << x );
return 0;
}
在包含<sstream>
之后,您可以使用此函數將int
轉換為std::string
:
#include <sstream>
string IntToString (int a)
{
stringstream temp;
temp<<a;
return temp.str();
}
您可能會在您的項目中包含 itoa 的實現。
這是 itoa 修改為與 std::string 一起使用: http : //www.strudel.org.uk/itoa/
#include <string>
#include <stdlib.h>
這是將 int 轉換為 string 的另一種簡單方法
int n = random(65,90);
std::string str1=(__String::createWithFormat("%c",n)->getCString());
您可以訪問此鏈接以獲取更多方法https://www.geeksforgeeks.org/what-is-the-best-way-in-c-to-convert-a-number-to-a-string/
假設我有integer = 0123456789101112
。 現在,這個整數可以被stringstream
類轉換成字符串。
這是 C++ 中的代碼:
#include <bits/stdc++.h>
using namespace std;
int main()
{
int n,i;
string s;
stringstream st;
for(i=0;i<=12;i++)
{
st<<i;
}
s=st.str();
cout<<s<<endl;
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.