itoa function problem

前端 未结 6 1127
北海茫月
北海茫月 2020-12-20 14:08

I\'m working on Eclipse inside Ubuntu environment on my C++ project.

I use the itoa function (which works perfectly on Visual Studio) and the compiler c

相关标签:
6条回答
  • 2020-12-20 14:12

    itoa depends on compiler, so better use the following methods :-

    method 1 :If you are using c++11, just go for std::to_string. It will do the trick.

    method 2 :sprintf works for both 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.

    C++ sprintf:

    int main ()
    {
    int i;
      char buffer [100];
      printf ("Enter a number: ");
      scanf ("%d",&i);
      sprintf(buffer, "%d", i);
      return 0;
    }`
    
    0 讨论(0)
  • 2020-12-20 14:16

    you may use 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;
    

    output would be :hell9

    0 讨论(0)
  • 2020-12-20 14:27

    www.cplusplus.com says:

    This function is not defined in ANSI-C and is not part of C++, but is supported by some compilers.

    Therefore, I'd strongly suggest that you don't use it. However, you can achieve this quite straightforwardly using stringstream as follows:

    stringstream ss;
    ss << myInt;
    string myString = ss.str();
    
    0 讨论(0)
  • 2020-12-20 14:29

    itoa() is not part of any standard so you shouldn't use it. There's better ways, i.e...

    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;
    }
    
    0 讨论(0)
  • 2020-12-20 14:29

    Did you include stdlib.h? (Or rather, since you're using C++, cstdlib)

    0 讨论(0)
  • 2020-12-20 14:37

    Boost way:

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

    0 讨论(0)
提交回复
热议问题