Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    New Coder
    Join Date
    Aug 2007
    Posts
    74
    Thanks
    3
    Thanked 2 Times in 2 Posts

    C++ Data type conversion

    Hello to all of guys ,

    I've got a question about C++ data type conversions .

    I wanna convert an int variable to string or generally put it into a string variable . What should I do ?

    How should I concatenate two strings in C++ to each other ? Is there any was except the strcat function ? I mean with something like an operator !?

    Will be really thankful to your help

  • #2
    Senior Coder
    Join Date
    Aug 2003
    Location
    One step ahead of you.
    Posts
    2,815
    Thanks
    0
    Thanked 3 Times in 3 Posts
    To "convert" an int to a string you should use string streams. C++ strings can be concatenated using the + operator.
    Code:
    #include <iostream>
    #include <string>
    #include <sstream>
    
    int main()
    {
    	using namespace std;
    
    	int number = 46;
    	string my_string;
    
    	ostringstream my_string_stream;
    
    	my_string_stream << number;
    	my_string = my_string_stream.str();
    
    	// Concatenate.
    	my_string = "The number is " + my_string;
    
    	cout << my_string << endl;
    }
    I'm not sure if this was any help, but I hope it didn't make you stupider.

    Experience is something you get just after you really need it.
    PHP Installation Guide Feedback welcome.

  • #3
    Regular Coder
    Join Date
    May 2004
    Location
    New Hampshire, America
    Posts
    246
    Thanks
    0
    Thanked 2 Times in 2 Posts
    Code:
    #include <iostream>
    #include <string>
    #include <sstream>
    #include <stdio>
    
    int main()
    {
    	using namespace std;
    
    	int number = 46;
    	string my_string;
           char the_number_string[20] = "";
    	
            ostringstream my_string_stream;
    
    	my_string_stream << number;
    	my_string = my_string_stream.str();
    
    	// Concatenate.
            sprintf(the_number_string, "%i", number);
    	my_string = "The number is " + the_number_string;
    
    	cout << my_string << endl;
    }
    Is that what you were looking for? Note: I typed my code in c++ non-.net so you have to make some slight modifications.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •