【问题标题】:itoa function problemitoa函数问题
【发布时间】:2011-04-17 12:12:22
【问题描述】:

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

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

我添加了<stdio.h><stdlib.h><iostream>,但这没有帮助。

【问题讨论】:

  • 请发布您的代码,没有它很难提供帮助
  • @CharlesB:这个问题在没有代码的情况下非常很容易诊断。此处无需贴代码。

标签: c++ portability itoa


【解决方案1】:

www.cplusplus.com 说:

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

因此,我强烈建议您不要使用它。但是,您可以使用stringstream 直接实现此目的,如下所示:

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

【讨论】:

  • 谢谢,我在 Visual Studio 中尝试过,但它无法识别它,我必须包含一些东西吗?
  • 错误 4 错误 C2079: 'streamstringKey' 使用未定义的类 'std::basic_stringstream<_elem>' h:\workspace\hw5\hw5\vehicle.cpp 151
  • 错误 8 错误 C2228: '.str' 左侧必须有类/结构/联合 h:\workspace\hw5\hw5\vehicle.cpp 154 错误 6 错误 C2297: 'const ' h:\workspace\hw5\hw5\vehicle.cpp 153 const string Vehicle::GetKey() const{ stringstream streamstringKey; streamstringKey string stringKey = streamstringKey.str();返回流字符串键; }
【解决方案2】:

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

【讨论】:

  • 实际上我需要将一个 int 附加到一个字符串。
  • 那么,我可以不使用ostringstream吗,因为我的编译器无法识别它。
【解决方案3】:

升压方式:

string str = boost::lexical_cast&lt;string&gt;(n);

【讨论】:

    【解决方案4】:

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

    方法一:如果你用的是c++11,就去std::to_string。它会成功的。

    方法 2 :sprintf 适用于 c 和 c++。 前任- 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;
    }`
    

    【讨论】:

      【解决方案5】:

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

      【讨论】:

        【解决方案6】:

        您是否包含了 stdlib.h? (或者更确切地说,因为您使用的是 C++,所以 cstdlib)

        【讨论】:

        • 这不一定有帮助,因为itoa 是非标准的。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-01-22
        • 1970-01-01
        • 1970-01-01
        • 2011-07-31
        • 1970-01-01
        • 2010-09-16
        相关资源
        最近更新 更多