12

我正在我的 C++ 项目的 Ubuntu 环境中使用 Eclipse。

我使用该itoa函数(在 Visual Studio 上完美运行)并且编译器抱怨itoa未声明。

我包括<stdio.h>, <stdlib.h><iostream>这没有帮助。

4

6 回答 6

11

www.cplusplus.com 说:

此函数未在 ANSI-C 中定义,也不是 C++ 的一部分,但受某些编译器支持。

因此,我强烈建议您不要使用它。但是,您可以使用stringstream以下方法非常简单地实现此目的:

stringstream ss;
ss << myInt;
string myString = ss.str();
于 2010-09-26T20:36:22.173 回答
7

itoa()不是任何标准的一部分,所以你不应该使用它。有更好的方法,即..

C:

int main() {
    char n_str[10];
    int n = 25;

    sprintf(n_str, "%d", n);

    return 0;
}

C++:

using namespace std;
int main() {
    ostringstream n_str;
    int n = 25;

    n_str << n;

    return 0;
}
于 2010-09-26T20:17:43.400 回答
5

升压方式:

string str = boost::lexical_cast<string>(n);

于 2010-09-26T21:00:45.080 回答
1

itoa 依赖于编译器,所以最好使用以下方法:-

方法1:如果你使用的是c++11,就去std::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;
}

注意 - 使用 -std=c++0x 编译。

C++ sprintf:

int main ()
{
int i;
  char buffer [100];
  printf ("Enter a number: ");
  scanf ("%d",&i);
  sprintf(buffer, "%d", i);
  return 0;
}`
于 2015-09-06T05:28:47.050 回答
1

你可以使用 sprintf

char temp[5];
temp[0]="h"
temp[1]="e"
temp[2]="l"
temp[3]="l"
temp[5]='\0'
sprintf(temp+4,%d",9)
cout<<temp;

输出将是:hell9

于 2017-07-18T06:14:29.773 回答
0

你包括stdlib.h吗?(或者更确切地说,因为您使用的是 C++,cstdlib)

于 2010-09-26T20:14:40.260 回答