[2 days left] What’s wrong with your cloud strategy? Learn why multicloud solutions matter with Nimble Storage.Register Now

x
?
Solved

How to convert an INTEGER to STRING - C++ Linux

Posted on 2004-03-25
29
Medium Priority
?
207,110 Views
Last Modified: 2013-12-14
This is my program
******************
#include <iostream>
using namespace std;

int main()
{
   int i = 0;
   string message = "";
   // message = the value of "i" converted to string.
   return 1;
}
********************

I want to convert "i" to string, how ? Please remember to add the class that I need to add...
0
Comment
Question by:probine
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 7
  • 5
  • 4
  • +6
29 Comments
 
LVL 8

Expert Comment

by:william_jwd
ID: 10676090
string message = itoa(i);
0
 

Author Comment

by:probine
ID: 10676105
Hello william_jwd.

I got this after using your code:

`itoa' undeclared (first use this function)

Any suggestion ? Do I need to incude some class ?
0
 
LVL 12

Expert Comment

by:stefan73
ID: 10676139
Hi probine,
You could use stringstream:

std::stringstream my_stringstream;
my_stringstream <<  i;

message = my_stringstream.str();

Cheers,

Stefan
0
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
LVL 12

Accepted Solution

by:
stefan73 earned 100 total points
ID: 10676142
probine,
> `itoa' undeclared (first use this function)

> Any suggestion ? Do I need to incude some class ?

itoa() is C API. Just do:

#include <stdlib.h>
0
 
LVL 8

Assisted Solution

by:william_jwd
william_jwd earned 100 total points
ID: 10676162
you should include stdlib.h
0
 

Author Comment

by:probine
ID: 10676219
My program:
********************
#include <iostream>
#include <stdlib.h>
using namespace std;

int main()
{
   int i = 0;
   string message = "";
   message = itoa(i);
   return 1;
}
**********************

When trying to compile with:   g++ test.cpp -o test  I get this error:
**********************
`itoa' undeclared (first use this function)
0
 

Author Comment

by:probine
ID: 10676246
Hi stefan73.

When trying to compile with streamstring I get this:

aggregate `std::stringstream my_stringstream' has incomplete type and cannot be defined

Do I need to include any specific class ?
0
 
LVL 14

Expert Comment

by:wayside
ID: 10676571
What compiler are you using?

For Microsoft, the function is

char *_itoa( int value,  char *string,  int radix);

Note the underscore.

Parameters:

value :Number to be converted.
string :String result.
radix :Base of value; must be in the range 2 – 36.

So do something like


int i = 123;
char buf[100];
_itoa(i, buf, 10);


buf now contains the string.
0
 

Author Comment

by:probine
ID: 10676612
FORGET IT..... I SAID LINUX ... Let me ask this now:

I have a program:

char * message;
string temp="HELLO"

How do I put the value "HELLO" in message ?
0
 
LVL 12

Expert Comment

by:stefan73
ID: 10676618
probine,
> Do I need to include any specific class ?

Yes, <sstream>
0
 
LVL 14

Expert Comment

by:wayside
ID: 10676662
> FORGET IT..... I SAID LINUX

Sorry, I missed that in the title.

> How do I put the value "HELLO" in message ?

message = temp.c_str();

0
 
LVL 14

Expert Comment

by:wayside
ID: 10676686
It needs to be const unless you cast it:

const char *message = temp.c_str();

or

char *message = (char *)temp.c_str();

The second method is dangerous if you plan on changing the contents of message.
0
 
LVL 12

Expert Comment

by:stefan73
ID: 10676687
> itoa() is C API. Just do:

Ouch, it's atoi, not itoa...

For itoa, you'll need sprintf(), which is not the C++ way to do it:


char* itoa(int input){
    static char buffer[16];

    snprintf(buffer,sizeof(buffer),"%d",input);

    return buffer;
}

(using snprintf here to avoid buffer overflows)
0
 

Author Comment

by:probine
ID: 10676701
To WAYSIDE:

While trying to compile:

invalid conversion from `const char*' to `char*'

0
 
LVL 14

Expert Comment

by:wayside
ID: 10676762
Can you post your code?
0
 

Author Comment

by:probine
ID: 10676890
My code is simple:
******************
#include <iostream>
using namespace std;

int main()
{
   char * message;
   string temp = "HELLO";
   // Here "message" should get the word "HELLO" .... how ?
   return 1;
}
**********************

How do I make my "message" to get the value of temp, so when I say:

cout << message

then I get "HELLO"    ?
0
 
LVL 12

Expert Comment

by:stefan73
ID: 10676937
probine,
> How do I make my "message" to get the value of temp, so when I say:

> cout << message

> then I get "HELLO"    ?

message=temp.c_str();
0
 
LVL 8

Expert Comment

by:william_jwd
ID: 10676950
Try this,

#include <iostream>
using namespace std;

int main()
{
   char * message;
   string temp = "HELLO";
   strcpy(message, temp);
   // Here "message" should get the word "HELLO" .... how ?
   return 1;
}
0
 

Author Comment

by:probine
ID: 10677024
Hi  william_jwd, I compile your program and I got this in complation time:

 cannot convert `std::string' to `const char*'

0
 
LVL 1

Expert Comment

by:ppk1981
ID: 10677324
Hi,

there are tooo many queries here ..

what about this ...

#include <iostream>
#include <stdlib.h>
using namespace std;

int main()
{
      int i = 10;
      string message = "";
      char IntStr[10] ;

      sprintf( IntStr, "%d", i ) ;
      message = IntStr;
      return 1;
}
0
 
LVL 1

Expert Comment

by:ppk1981
ID: 10677328
Hi,

there are tooo many queries here ..

what about this ...

#include <iostream>
#include <stdlib.h>
using namespace std;

int main()
{
      int i = 10;
      string message = "";
      char IntStr[10] ;

      sprintf( IntStr, "%d", i ) ;
      message = IntStr;
      return 1;
}

praveen
0
 
LVL 1

Expert Comment

by:ppk1981
ID: 10677350

I am Sorry .. I repeated it twise
0
 

Expert Comment

by:__Julien__
ID: 10677780
#include <iostream>
#include <string>
using namespace std;

int main()
{
   string temp = "HELLO";
   char* message = new char[temp.length() + 1];

   strcpy( message, temp.c_str() );
   cout << message;

   delete [] message;
   return 1;
}
0
 
LVL 17

Expert Comment

by:rstaveley
ID: 10685776
Wow what a confusing thread this has turned into.

Here's what you need:
--------8<--------
#include <iostream>
#include <sstream>

int main()
{
        int i = 0;
        std::ostringstream ostr;                                      // This is an output stream - cum - string
        ostr << i;                                                          // Output the number to the string stream
        std::string str = ostr.str();                                  // Get the output string
        std::cout << "Your string is \"" << str << "\"\n";  // Bob's your uncle
}
--------8<--------
0
 

Expert Comment

by:lyvanbao
ID: 11332876
In fact, the itoa function is not defined in ANSI C, but supported by some compilers like MSVC, but not g++ (see http://www.cplusplus.com/ref/cstdlib/itoa.html).

You can write your self this itoa function. In the following example, ___char *buff___ must be allocated before calling of this function.

char * itoa(int n, char *buff, int radix)
// convert a positive integer n to char *buff
// for instant, this function work with radix <= 10;
// a little change to run with radix > 10
{
      int q, r;
      int i = 0;
      char tmp[33];  // for radix = 2 and 32 bits computer
      do{
            q = int(n / radix);
            r = n % radix;
            n = q;
            tmp[i++] = 48 + r;
      }while(q > 0);
      int j;
      for(j = 0; j < i; j++){
            buff[j] = tmp[i - j - 1];
      }
      buff[j] = NULL;
      return buff;
}

Hope enjoy it.

0
 
LVL 40

Expert Comment

by:evilrix
ID: 20142663
More C++ like (not necessarily better)...

// What we want to convert
int i = 10;

// String stream to facilitate conversion
std::stringstream ssData;

// Convert to string (via stream)
ssData << i;

Of course, there is also boost::lexical_cast!
0

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

IntroductionThis article is the second in a three part article series on the Visual Studio 2008 Debugger.  It provides tips in setting and using breakpoints. If not familiar with this debugger, you can find a basic introduction in the EE article loc…
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
The viewer will learn how to pass data into a function in C++. This is one step further in using functions. Instead of only printing text onto the console, the function will be able to perform calculations with argumentents given by the user.
The viewer will be introduced to the technique of using vectors in C++. The video will cover how to define a vector, store values in the vector and retrieve data from the values stored in the vector.

656 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question