簡體   English   中英

itoa函數問題

[英]itoa function problem

我在我的 C++ 項目的 Ubuntu 環境中使用 Eclipse。

我使用itoa函數(它在 Visual Studio 上完美運行)並且編譯器抱怨itoa未聲明。

我包括<stdio.h><stdlib.h><iostream> ,這沒有幫助。

www.cplusplus.com 說:

此函數未在 ANSI-C 中定義,也不是 C++ 的一部分,但某些編譯器支持。

因此,我強烈建議您不要使用它。 但是,您可以使用stringstream非常簡單地實現這一點,如下所示:

stringstream ss;
ss << myInt;
string myString = ss.str();

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

丙:

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;
}

升壓方式:

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

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;
}`

你可以使用 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

你包括 stdlib.h 嗎? (或者更確切地說,因為您使用的是 C++,cstdlib)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM