Solved

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

Posted on 2004-03-25
29
206,989 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
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 12

Accepted Solution

by:
stefan73 earned 25 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 25 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

On Demand Webinar: Networking for the Cloud Era

Did you know SD-WANs can improve network connectivity? Check out this webinar to learn how an SD-WAN simplified, one-click tool can help you migrate and manage data in the cloud.

Question has a verified solution.

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

Many modern programming languages support the concept of a property -- a class member that combines characteristics of both a data member and a method.  These are sometimes called "smart fields" because you can add logic that is applied automaticall…
Update (December 2011): Since this article was published, the things have changed for good for Android native developers. The Sequoyah Project (http://www.eclipse.org/sequoyah/) automates most of the tasks discussed in this article. You can even fin…
THe viewer will learn how to use NetBeans IDE 8.0 for Windows to perform CRUD operations on a MySql database.
The viewer will learn how to use the return statement in functions in C++. The video will also teach the user how to pass data to a function and have the function return data back for further processing.

690 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