Thread: A simple printing question

  1. #1
    Registered User
    Join Date
    Oct 2003
    Posts
    104

    A simple printing question

    Okay I know somtimes we make a mistake with even the simplest thing!

    Im trying to print out a string followed by an integer value, but don't want to print it out directely to the screen as I am using it in a function.

    int percent;

    cout << "Percantage " << percent;

    works,

    but

    string str = "Percentage" + percent;
    cout << str;


  2. #2
    Registered User Micko's Avatar
    Join Date
    Nov 2003
    Posts
    715
    You need to convert percent to string. See the FAQ
    A quick code:
    Code:
    #include<iostream>
    #include<sstream>
    using namespace std;
    
    int main()
    {
    	
    	ostringstream ostr;
    	double num = 15.5;
    
    	ostr << num;
    
    	string percent_str =  ostr.str();
            cout<<"Percent "+ percent_str;
    	
    	return 0;
    }
    Last edited by Micko; 04-01-2006 at 03:06 PM.
    Gotta love the "please fix this for me, but I'm not going to tell you which functions we're allowed to use" posts.
    It's like teaching people to walk by first breaking their legs - muppet teachers! - Salem

  3. #3
    Registered User
    Join Date
    Oct 2003
    Posts
    104
    but that is outputting the string directly to the screen, i want to be able to store it as a string as i wouldbe using that to display via another function. I thougt if u you the concat operator + with a string and a number it would automatically convert the number to a string and concantenate it?

  4. #4
    Registered User Kirdra's Avatar
    Join Date
    Aug 2002
    Posts
    105
    string str = "Percentage ";
    str += percent;

  5. #5
    #define WORLD "sad place" LinuxCoder's Avatar
    Join Date
    Mar 2006
    Location
    Portugal
    Posts
    89
    Quote Originally Posted by Kirdra
    string str = "Percentage ";
    str += percent;
    I believe this won't work since the concatenation operator will only accept char*, char or std::string so i believe you must always work with something like Micko suggested to convert the int (or any other type) to any of the accepted types, being std::string the easier one to achieve.

    Cheers

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Simple class question
    By 99atlantic in forum C++ Programming
    Replies: 6
    Last Post: 04-20-2005, 11:41 PM
  2. Simple question about pausing program
    By Noid in forum C Programming
    Replies: 14
    Last Post: 04-02-2005, 09:46 AM
  3. simple question.
    By InvariantLoop in forum Windows Programming
    Replies: 4
    Last Post: 01-31-2005, 12:15 PM
  4. Binary Search Trees Part III
    By Prelude in forum A Brief History of Cprogramming.com
    Replies: 16
    Last Post: 10-02-2004, 03:00 PM
  5. simple fgets question
    By theweirdo in forum C Programming
    Replies: 7
    Last Post: 01-27-2002, 06:58 PM