C++ itoa函数问题
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3799595/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
itoa function problem
提问by Aviadjo
I'm working on Eclipse inside Ubuntu environment on my C++ project.
我在我的 C++ 项目的 Ubuntu 环境中使用 Eclipse。
I use the itoa
function (which works perfectly on Visual Studio) and the compiler complains that itoa
is undeclared.
我使用了该itoa
函数(在 Visual Studio 上完美运行)并且编译器抱怨itoa
未声明。
I included <stdio.h>
, <stdlib.h>
, <iostream>
which doesn't help.
我包括<stdio.h>
, <stdlib.h>
,<iostream>
这没有帮助。
采纳答案by Component 10
www.cplusplus.com says:
www.cplusplus.com 说:
This function is not defined in ANSI-C and is not part of C++, but is supported by some compilers.
此函数未在 ANSI-C 中定义,也不是 C++ 的一部分,但某些编译器支持。
Therefore, I'd strongly suggest that you don't use it. However, you can achieve this quite straightforwardly using stringstream
as follows:
因此,我强烈建议您不要使用它。但是,您可以使用stringstream
以下方法非常简单地实现这一点:
stringstream ss;
ss << myInt;
string myString = ss.str();
回答by David Titarenco
itoa()
is not part of any standard so you shouldn't use it. There's better ways, i.e...
itoa()
不是任何标准的一部分,所以你不应该使用它。有更好的方法,即..
C:
C:
int main() {
char n_str[10];
int n = 25;
sprintf(n_str, "%d", n);
return 0;
}
C++:
C++:
using namespace std;
int main() {
ostringstream n_str;
int n = 25;
n_str << n;
return 0;
}
回答by dimba
Boost way:
升压方式:
string str = boost::lexical_cast<string>(n);
string str = boost::lexical_cast<string>(n);
回答by Shaky99
itoa depends on compiler, so better use the following methods :-
itoa 取决于编译器,因此最好使用以下方法:-
method 1 :If you are using c++11, just go for std::to_string. It will do the trick.
方法 1:如果您使用的是 c++11,只需使用 std::to_string。它会解决问题。
method 2 :sprintf works for both c & c++. ex- ex - to_string
方法 2 :sprintf 适用于 C 和 C++。ex- ex - to_string
#include <bits/stdc++.h>
using namespace std;
int main ()
{
int i;
char buffer [100];
printf ("Enter a number: ");
scanf ("%d",&i);
string str = to_string(i);
strcpy(buffer, str.c_str());
cout << buffer << endl;
return 0;
}
Note - compile using -std=c++0x.
注意 - 使用 -std=c++0x 编译。
C++ sprintf:
C++ sprintf:
int main ()
{
int i;
char buffer [100];
printf ("Enter a number: ");
scanf ("%d",&i);
sprintf(buffer, "%d", i);
return 0;
}`
回答by pari
you may use sprintf
你可以使用 sprintf
char temp[5];
temp[0]="h"
temp[1]="e"
temp[2]="l"
temp[3]="l"
temp[5]='##代码##'
sprintf(temp+4,%d",9)
cout<<temp;
output would be :hell9
输出将是:hell9
回答by Martin T?rnwall
Did you include stdlib.h? (Or rather, since you're using C++, cstdlib)
你包括 stdlib.h 吗?(或者更确切地说,因为您使用的是 C++,cstdlib)