我在想是否有一种替代方法来将整数转换为字符串,因为当我在Visual Studio中运行itoa()
时会收到警告,并且当我尝试在Linux下构建我的程序时,会出现编译错误。
我在想是否有一种替代方法来将整数转换为字符串,因为当我在Visual Studio中运行itoa()
时会收到警告,并且当我尝试在Linux下构建我的程序时,会出现编译错误。
C++11中可以使用std::to_string
函数:
#include <string>
std::string s = std::to_string(5);
如果您使用的是C++11之前的版本,您可以使用C++流:
#include <sstream>
int i = 5;
std::string s;
std::stringstream out;
out << i;
s = out.str();
本文摘自http://notfaq.wordpress.com/2006/08/30/c-convert-int-to-string/
boost::to_string
http://www.boost.org/doc/libs/1_51_0/boost/exception/to_string.hpp - alfCboost::lexical_cast 的效果非常好。
#include <boost/lexical_cast.hpp>
int main(int argc, char** argv) {
std::string foo = boost::lexical_cast<std::string>(argc);
}
itoa是一个非标准的辅助函数,旨在补充atoi标准函数,并可能隐藏一个sprintf(大多数其功能都可以用sprintf实现):http://www.cplusplus.com/reference/clibrary/cstdlib/itoa.html
使用sprintf。 或snprintf。 或您找到的任何工具。
尽管某些函数不在标准中,如“onebyone”在其中一条评论中所提到的那样,但大多数编译器都会为您提供替代方案(例如Visual C ++有自己的_snprintf,如果需要,可以将其typedef为snprintf)。
使用C ++流(在当前情况下为std :: stringstream(甚至是Herb Sutter在他的书中提出的已弃用的std :: strstream,因为它略快))。
您正在使用C ++,这意味着您可以选择想要的方式:
更快的方式(即C的方式),但您应该确保代码是应用程序的瓶颈(过早的优化是有害的等等),并且您的代码是安全地封装以避免风险Buffer overruns。
更安全的方式(即C ++的方式),如果您知道此代码部分不是关键性的,则最好确保此代码部分不会在随机时刻中断,因为有人误解了大小或指针(在现实生活中发生,像...昨天,在我的电脑上,因为有人认为它“酷”而使用了更快的方式,而没有真正需要它)。
1
在我的帖子中,我提到了sprintf及其安全变体,而不仅仅是sprintf。2
知道你的代码在哪里编译并不是一项不可能完成的任务(在我这种情况下,最差的情况是Windows/VC++、Solaris/CC和Linux/g++,最好的情况是仅限于Windows/VC++)。3
你所描述的世界是试图破坏你的代码的破坏者成为了常态。我的世界由普通开发人员组成,因此花费时间通过重写每个API的“安全”版本来保护我的代码免受破坏者攻击是没有生产力的。[...] - paercebal结论
使用手头最好的工具。如果最好的工具是隐藏在包装类或函数中的sprintf……现在,如果你主张将sprintf重写作为这个问题的答案,请随意编写你自己的答案。我不确定问题的作者是否会阅读所有的评论。 - paercebal尝试使用sprintf():
char str[12];
int num = 3;
sprintf(str, "%d", num); // str now contains "3"
sprintf() 函数类似于 printf(),但输出字符串。
此外,正如 Parappa 在评论中提到的那样,您可能需要使用 snprintf() 来防止缓冲区溢出(发生在您要转换的数字不适合您字符串大小的情况下)。它的工作原理如下:
snprintf(str, sizeof(str), "%d", num);
在幕后,lexical_cast 实际上是这样实现的:
std::stringstream str;
str << myint;
std::string result;
str >> result;
如果您不想为此引入boost,则使用上述方法是一个很好的解决方案。str.str()
就足够时,它是否会流入字符串中。 - sbi我们可以在C++中定义自己的iota
函数,如下:
string itoa(int a)
{
string ss=""; //create empty string
while(a)
{
int x=a%10;
a/=10;
char i='0';
i=i+x;
ss=i+ss; //append new character at the front of the string!
}
return ss;
}
不要忘记 #include <string>
。
template <typename T> string toStr(T tmp)
{
ostringstream out;
out << tmp;
return out.str();
}
template <typename T> T strTo(string tmp)
{
T output;
istringstream in(tmp);
in >> output;
return output;
}
请尝试使用高质量的C++库Boost.Format或FastFormat:
int i = 10;
std::string result;
使用Boost.Format
result = str(boost::format("%1%", i));
fastformat::fmt(result, "{0}", i);
fastformat::write(result, i);
通过一个聪明地编写的模板函数,您可以将任何内容转换为字符串。此代码示例使用循环在Win-32系统中创建子目录。使用字符串连接运算符operator+将根与后缀连接起来以生成目录名称。后缀是通过将循环控制变量i转换为C++字符串来创建的,使用模板函数,并将其与另一个字符串连接。
//Mark Renslow, Globe University, Minnesota School of Business, Utah Career College
//C++ instructor and Network Dean of Information Technology
#include <cstdlib>
#include <iostream>
#include <string>
#include <sstream> // string stream
#include <direct.h>
using namespace std;
string intToString(int x)
{
/**************************************/
/* This function is similar to itoa() */
/* "integer to alpha", a non-standard */
/* C language function. It takes an */
/* integer as input and as output, */
/* returns a C++ string. */
/* itoa() returned a C-string (null- */
/* terminated) */
/* This function is not needed because*/
/* the following template function */
/* does it all */
/**************************************/
string r;
stringstream s;
s << x;
r = s.str();
return r;
}
template <class T>
string toString( T argument)
{
/**************************************/
/* This template shows the power of */
/* C++ templates. This function will */
/* convert anything to a string! */
/* Precondition: */
/* operator<< is defined for type T */
/**************************************/
string r;
stringstream s;
s << argument;
r = s.str();
return r;
}
int main( )
{
string s;
cout << "What directory would you like me to make?";
cin >> s;
try
{
mkdir(s.c_str());
}
catch (exception& e)
{
cerr << e.what( ) << endl;
}
chdir(s.c_str());
//Using a loop and string concatenation to make several sub-directories
for(int i = 0; i < 10; i++)
{
s = "Dir_";
s = s + toString(i);
mkdir(s.c_str());
}
system("PAUSE");
return EXIT_SUCCESS;
}