Skip to main content
gamedev.net
🔒 Locked

C - C++ (string question)

Started by eedok Oct 18, 2005 at 12:13 PM 2 replies 3.6k views
Original Post
eedok
eedok
Well I'm trying to learn C++ and break my C and java habits, So I've got this question, what's the equivelant of sprintf(string,"The total is $%.2f",total); in C++ using std:string? I know to do this in java you use the DecimalFormat Class to make the precision correct then just use the + operator to add the float to the string, but C++ doesn't seem to allow you to do this, so how is it done?
Enigma
Enigma
#include <iomanip>#include <iostream>#include <sstream>#include <boost/format.hpp>int main(){	{ // using manipulators		float total = 3.71f;		std::ostringstream sstr;		sstr << "The total is $" << std::setiosflags(std::ios::fixed) << std::setprecision(2) << total;		std::string string = sstr.str();		std::cout << string << '\n';	}	{ // using stringstream member functions		float total = 3.71f;		std::ostringstream sstr;		sstr.flags(std::ios::fixed);		sstr.precision(2);		sstr << "The total is $" << total;		std::string string = sstr.str();		std::cout << string << '\n';	}	{ // alternative - using boost::format		float total = 3.71f;		boost::format format("The total is $%.2f");		std::string string = (format % total).str();		std::cout << string << '\n';	}}

Enigma

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.