Thread: Conversion to string

  1. #1
    Registered User
    Join Date
    Sep 2007
    Posts
    119

    Conversion to string

    I have no idea how to convert integers, doubles, floats etc... to strings. Can anyone help? I thought maybe casting might do it...I googled the "string class" for C++ but it makes no mention of what I'm trying to do. Has a lot of useful information though. I also thought simply using string = int would do it, but no luck. Are those functions atoi() or itoa() my only option??

    Code:
    #include <iostream>
    #include <stdlib.h>
    #include <string>
    
    using namespace std;
    
    int main ()
    {
    	string test;
    	int num = 5;
    	double num2 = 10.5;
    
    	test = (string)num;
    	cout << test;
    
    	test = (string)num2;
    	cout << test;
    
      return (EXIT_SUCCESS);
    
    }

  2. #2
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    You can "write" your value to a "stringstream" and read it back out as a string, if you wish.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  3. #3
    Registered User
    Join Date
    Sep 2007
    Posts
    119
    sounds good...how? haha, sorry i'm not familiar with doing that.

  4. #4
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    soemthing like this:
    Code:
    #include <stringstream>
    ...
       stringstream ss;
    
       float f = 15.36;
    
       string str;
      
       ss << f;
    
       ss >> str;
    ...
    The above is to give you an idea, not a complete compilable sample - you will have to work on that.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  5. #5

  6. #6
    Jack of many languages Dino's Avatar
    Join Date
    Nov 2007
    Location
    Chappell Hill, Texas
    Posts
    2,332
    This question just came up yesterday.

    http://cboard.cprogramming.com/showthread.php?t=99006
    Mainframe assembler programmer by trade. C coder when I can.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Message class ** Need help befor 12am tonight**
    By TransformedBG in forum C++ Programming
    Replies: 1
    Last Post: 11-29-2006, 11:03 PM
  2. Replies: 4
    Last Post: 03-03-2006, 02:11 AM
  3. Program using classes - keeps crashing
    By webren in forum C++ Programming
    Replies: 4
    Last Post: 09-16-2005, 03:58 PM
  4. creating class, and linking files
    By JCK in forum C++ Programming
    Replies: 12
    Last Post: 12-08-2002, 02:45 PM
  5. Again Character Count, Word Count and String Search
    By client in forum C Programming
    Replies: 2
    Last Post: 05-09-2002, 11:40 AM