int'ten string'e Dönüşüm
C++'ta bir şeyler yaparken kimi zaman bir int'i string'e dönüştürmek isteyebilirsiniz. Bunu yapmak için sanırım en ideal yollardan biri aşağıda yer alıyor. Uçuk kaçık bir kütüphane vs. kullanmayan farklı bir yöntem biliyorsanız belirtmekten çekinmeyiniz.
Ya da şöyle de olabilir, benzer şekilde:
İki uygulamanın çıktısı da aşağıdaki gibi olacaktır:
Kaynaklar:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <sstream> | |
int main() | |
{ | |
int i = 5; | |
std::string s; | |
std::stringstream out; | |
out << i; | |
s = out.str(); | |
std::cout << i + i << std::endl; | |
std::cout << s + s << std::endl; | |
} |
Ya da şöyle de olabilir, benzer şekilde:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <sstream> | |
template <class T> inline std::string to_string (const T& t) | |
{ | |
std::stringstream ss; | |
ss << t; | |
return ss.str(); | |
} | |
int main() | |
{ | |
int i = 5; | |
std::cout << i + i << std::endl; | |
std::cout << to_string(i) + to_string(i) << std::endl; | |
} |
İki uygulamanın çıktısı da aşağıdaki gibi olacaktır:
10Biraz daha bakınınca Boost ile daha kısa, daha güzel ve daha olması gerektiği gibi bir yol olduğunu gördüm. Bu da tercih edilebilir eğer Boost kullanmak sorun olmayacaksa.
55
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <boost/lexical_cast.hpp> | |
int main() | |
{ | |
int i = 5; | |
std::string foo = boost::lexical_cast<std::string>(i); | |
std::cout << i + i << std::endl; | |
std::cout << foo + foo << std::endl; | |
} |
Kaynaklar:
std::string::to_string( i ); şeklindede string ifade döner. Hiç uğraşmaya değmez.
YanıtlaSilEvet C++11 ile birlikte uğraşmaya gerek yok.
Silhttp://en.cppreference.com/w/cpp/string/basic_string/to_string