Change int to string

This is a discussion on Change int to string within the C++ Programming forums, part of the General Programming Boards category; I'm new to programming so sorry if this is an easy question. But how do I change and int variable ...

  1. #1
    Registered User
    Join Date
    Feb 2005
    Posts
    1

    Change int to string

    I'm new to programming so sorry if this is an easy question. But how do I change and int variable to a string variable?

  2. #2
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,801
    Use a stringstream:

    Code:
    #include <string>
    #include <sstream>
    #include <iostream>
    
    int main()
    {
        int value = 100;
        std::stringstream sstr;
        sstr << value;                  // Store integer in stringstream
        std::string str = sstr.str();   // Convert stringstream to string
        std::cout << str << std::endl;  // Output string
    }
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

  3. #3
    Banned
    Join Date
    Oct 2004
    Posts
    250
    Also you can use itoa(); Im not sure but i think itoa() might be windows specific so it might be a better option to use stringstream.

    Code:
    string buffer;
    int number = 0;
    itoa(number,buffer,10);

  4. #4
    Super Moderator
    Join Date
    Sep 2001
    Posts
    4,913
    I think you're thinking of atoi(), which is standard (stdlib), does the opposite, and wouldn't work with STL strings even if it did exist (unless of course windows.h includes this function, but I doubt it).

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Drawing Program
    By Max_Payne in forum C++ Programming
    Replies: 21
    Last Post: 12-21-2007, 04:34 PM
  2. Screwy Linker Error - VC2005
    By Tonto in forum C++ Programming
    Replies: 5
    Last Post: 06-19-2007, 02:39 PM
  3. Replies: 2
    Last Post: 03-24-2006, 07:36 PM
  4. getting a headache
    By sreetvert83 in forum C++ Programming
    Replies: 41
    Last Post: 09-30-2005, 05:20 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21