Solved

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

Posted on 2004-03-25
29
206,857 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
  • 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
 
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
What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 

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

What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

Join & Write a Comment

Introduction This article is a continuation of the C/C++ Visual Studio Express debugger series. Part 1 provided a quick start guide in using the debugger. Part 2 focused on additional topics in breakpoints. As your assignments become a little more …
This article shows you how to optimize memory allocations in C++ using placement new. Applicable especially to usecases dealing with creation of large number of objects. A brief on problem: Lets take example problem for simplicity: - I have a G…
The goal of the tutorial is to teach the user how to use functions in C++. The video will cover how to define functions, how to call functions and how to create functions prototypes. Microsoft Visual C++ 2010 Express will be used as a text editor an…
The viewer will be introduced to the member functions push_back and pop_back of the vector class. The video will teach the difference between the two as well as how to use each one along with its functionality.

757 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

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now