I'm testing using this_thread::sleep_for() to create an object that acts similarly to cout, except when printing strings it will have a small delay between each character. However, instead of waiting 0.1 seconds between each character, it waits about a second then prints it all at once. Here's my code:
#include <iostream>
#include <chrono>
#include <thread>
class OutputObject
{
int speed;
public:
template<typename T>
void operator<<(T out)
{
std::cout << out;
}
void operator<<(const char *out)
{
int i = 0;
while(out[i])
{
std::this_thread::sleep_for(std::chrono::milliseconds(speed));
std::cout << out[i];
++i;
}
}
void operator=(int s)
{
speed = s;
}
};
int main(int argc, char **argv)
{
OutputObject out;
out = 100;
out << "Hello, World!\n";
std::cin.get();
return 0;
}
Any idea what I'm doing wrong?
Edit: CoryKramer pointed out that std::flush is required for it to act in real time. By changing std::cout << out[i]; to std::cout << out[i] << std::flush;, I solved my problem!
Streams have buffer, so cout won't print text before you flush stream, for example endl flushes stream and adds '\n' also call to cin automatically flushes buffered data in stream. Try to use this:
while(out[i])
{
std::this_thread::sleep_for(std::chrono::milliseconds(speed));
std::cout << out[i];
std::cout.flush();
++i;
}
Related
Below code is the normal way to get the input from a text and store it in an array in a structure.
Wanted to ask how can i use pointer to store all these data into the array of structure ? Like p1->Years (this is without array, but how can i apply this to way of writing in below code)
Any better suggestion to use pointer to take in the input?
int years = 4;
struct maju_company {
int Year;
float quarter1, quarter2, quarter3, quarter4, total_sales, average_sales;
};
int main() {
string line;
maju_company p1[years];
fstream yeecinnfile("MajuSales.txt");
if(yeecinnfile.is_open()) {
//ignoring the first four line of code and store the rest of the code
string line1,line2,line3,line4;
getline(yeecinnfile,line1);
getline(yeecinnfile,line2);
getline(yeecinnfile,line3);
getline(yeecinnfile,line4);
while(!yeecinnfile.eof()) {
for(int i =0; i<years; i++) {
yeecinnfile>>p1[i].Year>>p1[i].quarter1>>p1[i].quarter2>>p1[i].quarter3>>p1[i].quarter4;
}
}
for(int i =0; i<years; i++) {
cout<<p1[i].Year<<setw(10)<<p1[i].quarter1<<setw(10)<<p1[i].quarter2<<setw(10)<<p1[i].quarter3<<setw(10)<<p1[i].quarter4<<endl;
}
cout<<endl;
}
}
I see nothing wrong with the way you do this.
However, you could create a pointer to each record inside the loop
maju_company* p = &p1[i];
and then use p-> instead of p1[i]., but I really don't see this as an improvement.
If the reading loop looks too complicated, I would rather move the code to a separate function, perhaps
void read_record(maju_company& company);
or maybe
maju_company read_record();
and then only have to handle a single company inside the function (so no indexing and no ponters there).
I think you wouldn't need pointers at all for your example.
Use a std::vector to hold all your data and then there are other
things from C++ I think you should learn to use, example here :
(if you have questions let me know)
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
// dont use : using namespace std;
struct maju_company_data
{
int year;
float quarter1, quarter2, quarter3, quarter4, total_sales, average_sales;
};
// describe how to stream data to an output stream (like std::cout)
std::ostream& operator<<(std::ostream& os, const maju_company_data& data)
{
os << "-----------------------------------------------------\n";
os << "Company data for year : " << data.year << "\n";
os << "Quarter 1 : " << data.quarter1 << "\n";
os << "Quarter 2 : " << data.quarter1 << "\n";
os << "Quarter 3 : " << data.quarter1 << "\n";
os << "Quarter 4 : " << data.quarter1 << "\n";
os << "\n";
return os;
}
int main()
{
// no need to manage pointers yourself use a vector
std::vector<maju_company_data> company_yearly_data; // give variables a meaningful name
std::ifstream ifile("MajuSales.txt"); // ifstream your using file as input
std::string line1, line2, line3, line4;
// ignore first line
ifile >> line1;
while (ifile >> line1 >> line2 >> line3 >> line4) // probably you need to read a few more lines here
{
maju_company_data data;
// convert read strings to numbers
data.year = std::stoi(line1);
data.quarter1 = std::stof(line2);
data.quarter2 = std::stof(line3);
data.quarter3 = std::stof(line4);
//..
//data.quarter4 = std::stof(line5);
//data.total_sales = std::stof(line6);
company_yearly_data.push_back(data);
};
// this is a range based for loop
// it is prefered since you cant go out of bounds
// const auto& means that data will be an unmodifiable
// reference to each of the structs stored in the vector
for (const auto& data : company_yearly_data)
{
std::cout << data; // since we overloaded << this loop will be nice and clean
}
return 0;
}
A C++ approach to this to overload the istream operator>> and ostream operator<< for your specific type. E.g.
#include <algorithm>
#include <array>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <iterator>
#include <string>
static constexpr auto years{4};
struct maju_company {
int Year{};
float quarter1{}, quarter2{}, quarter3{}, quarter4{};
float total_sales{}, average_sales{}; // ALWAYS init your floats.
};
auto& operator>>(std::istream& is, maju_company& mc) {
is >> mc.Year
>> mc.quarter1 >> mc.quarter2 >> mc.quarter3 >> mc.quarter4
>> mc.total_sales >> mc.average_sales;
return is;
}
auto& operator<<(std::ostream& os, maju_company const& mc) {
os << mc.Year
<< std::setw(10) << mc.quarter1
<< std::setw(10) << mc.quarter2
<< std::setw(10) << mc.quarter3
<< std::setw(10) << mc.quarter4;
return os;
}
You can then go on to use the type using the std library, e.g.
int main() {
auto p1{std::array<maju_company, years>{}};
{
auto fs{std::fstream("MajuSales.txt")};
if (!fs.is_open()) return -1;
{
// throw away 4 lines
auto dummy{std::string{}};
for (auto i{0}; i < 4; ++i) getline(fs, dummy);
}
std::copy_n(std::istream_iterator<maju_company>{fs},
years,
begin(p1));
}
std::copy(cbegin(p1), cend(p1),
std::ostream_iterator<maju_company>{std::cout, "\n"});
}
What I try to do is to write all output inside a function into a file. Maybe I need a way to assign all output (not only arrays) in test_func to some kind of variable so that I can return it, but I can't figure out.
#include <iostream>
#include <fstream>
#include <functional>
using namespace std;
void test_func()
{
int a[] = {20,42,41,40};
int b[] = {2,4,2,1};
cout << "Below is the result: "<< endl;
for (int i=0; i<4; i++){
cout << "***********************" << endl;
cout << a[i] << " : " << b[i] <<endl;
cout << "-----------------------" << endl;
}
}
void write_to_file(function<void()>test_func)
{
ofstream ofile;
ofile.open("abc.txt");
ofile << test_func(); // This is not allowed
ofile.close();
}
int main()
{
write_to_file(test_func);
return 0;
}
I need to get all output from test_func instead of only the array a and b, because I have multiple functions in different formats, which are all needed to write into the file using same function write_to_file.
Is there any logical way to do this? (or alternative to function?)
Here is some code that will work the way you want. You have to replace std::couts current rdbuf() with the one of the file streams, and reset it afterwards:
void write_to_file(function<void()>test_func) {
ofstream ofile;
ofile.open("abc.txt");
std::streambuf* org = cout.rdbuf(); // Remember std::cout's old state
cout.rdbuf(ofile.rdbuf()); // Bind it to the output file stream
test_func(); // Simply call the anonymous function
cout.rdbuf(org); // Reset std::cout's old state
ofile.close();
}
Here you can see it running as you intended: Demo
To overcome the problem with the varying function signatures, you can use a delegating lambda function:
void test_func2(double a, int b) {
cout << a << " * " << b << " = " << (a * b) << endl;
}
int main() {
// Create a lambda function that calls test_func2 with the appropriate parameters
auto test_func_wrapper = []() {
test_func2(0.356,6);
};
write_to_file(test_func_wrapper); // <<<<< Pass the lambda here
// You can also forward the parameters by capturing them in the lambda definition
double a = 0.564;
int b = 4;
auto test_func_wrapper2 = [a,b]() {
test_func2(a,b);
};
write_to_file(test_func_wrapper2);
return 0;
}
Demo
You can even do this with a little helper class, which generalizes the case for any std::ostream types:
class capture {
public:
capture(std::ostream& out_, std::ostream& captured_) : out(out_), captured(captured_), org_outbuf(captured_.rdbuf()) {
captured.rdbuf(out.rdbuf());
}
~capture() {
captured.rdbuf(org_outbuf);
}
private:
std::ostream& out;
std::ostream& captured;
std::streambuf* org_outbuf;
};
void write_to_file(function<void()>test_func)
{
ofstream ofile;
ofile.open("abc.txt");
{
capture c(ofile,cout); // Will cover the current scope block
test_func();
}
ofile.close();
}
Demo
So regarding your comment:
Sure, but I will require something to store those cout, or maybe there's another completely different way instead of using test_func() for the process?
We have everything at hand now to do this
#include <iostream>
#include <fstream>
#include <functional>
#include <string>
#include <sstream>
using namespace std;
void test_func1(const std::string& saySomething) {
cout << saySomething << endl;
}
void test_func2(double a, int b) {
cout << "a * b = " << (a * b) << endl;
}
class capture {
public:
capture(std::ostream& out_, std::ostream& captured_) : out(out_), captured(captured_), org_outbuf(captured_.rdbuf()) {
captured.rdbuf(out.rdbuf());
}
~capture() {
captured.rdbuf(org_outbuf);
}
private:
std::ostream& out;
std::ostream& captured;
std::streambuf* org_outbuf;
};
int main() {
std::string hello = "Hello World";
auto test_func1_wrapper = [hello]() {
test_func1(hello);
};
double a = 0.356;
int b = 6;
auto test_func2_wrapper = [a,b]() {
test_func2(a,6);
};
std::stringstream test_func1_out;
std::stringstream test_func2_out;
std::string captured_func_out;
{ capture c(test_func1_out,cout);
test_func1_wrapper();
}
{ capture c(test_func2_out,cout);
test_func2_wrapper();
}
captured_func_out = test_func1_out.str();
cout << "test_func1 wrote to cout:" << endl;
cout << captured_func_out << endl;
captured_func_out = test_func2_out.str();
cout << "test_func2 wrote to cout:" << endl;
cout << captured_func_out << endl;
}
And the Demo of course.
The line ofile << test_func(); means that returned value of called test_func(); is directed to that stream. It doesn't do anything to actions done within function called. You may pass stream to the function though.
void test_func(ostream& outs)
{
outs << "Below is the result: "<< endl;
}
and call it with cout or ofile - any ostream as argument.
void write_to_file(function<void(ostream&)>test_func)
{
ofstream ofile;
ofile.open("abc.txt");
test_func(ofile); // This is not allowed
ofile.close();
}
But if the behaviour of function as stream manipulator is something what you want, you have to design a proper operator.
ostream& operator<< (ostream& o, void(*func)(ostream&) )
{
func(o);
return o;
}
Then you can write something like
cout << test_func << " That's all, folks\n";
Note, that test_func isn't called here, its id used as expression results in function's address being passed to operator<<.
Real stream manipulators (e.g. https://en.cppreference.com/w/cpp/io/manip/setw ) implemented not as functions , but as templates of functional objects, the argument of setw in line:
is >> std::setw(6) >> arr;
is actually argument of a constructor
What I try to do is to write all output inside a function into a file.
I often use a std::stringstream to act as a temporary repository for text, i.e. the ss holds and bundles all output into a 'buffer' (a text string) for delay'd output to the file.
For your test_func, you might add a ss reference parameter :
void test_func(std::stringsteam& ss)
{
int a[] = {20,42,41,40};
int b[] = {2,4,2,1};
cout << "Below is the result: "<< endl;
for (int i=0; i<4; i++){
ss << "***********************" << endl;
ss << a[i] << " : " << b[i] <<endl;
ss << "-----------------------" << endl;
}
}
A std::stringstream is essentially a ram-based ofile (with none of the hard disk overhead).
So you can run many test_func's, lump all the output together into one ss, and empty the ss content to the one file.
Or, you might invoke 1 test_func, output / append that ss contents to your ofile, then clear the ss for re-use.
You also might invoke 1 test func, output that ss contents to a unique ofile, then clear the ss and do the next test func, etc.
Note: a) std::stringstream uses one std::string as a working buffer, and b) std::string keeps its data in dynamic memory. I seldom worry about how big the ss gets. But, if you are worried, and have an estimate, you can easily use reserve to set the string size. Knowing this size will allow you to plan to control very big output files.
Next, consider keeping stringstream out of the test_func's, and instead keep it in the outer data gathering function:
void write_to_file(function<void()>test_func)
{
std::stringstream ss; // temporary container
test_func(ss); // add contributions
test_func2(ss); // add contributions
test_func3(ss); // add contributions
// ...
test_funcN(ss); // add contributions
// when all testing is complete, output concatenated result to single file
ofstream ofile;
ofile.open("abc.txt");
ofile << ss.str();
ofile.close();
}
int main()
{
write_to_file(test_func);
return 0;
}
Note: to empty a ss, I use 2 steps:
void ssClr(stringstream& ss) { ss.str(string()); ss.clear(); }
// clear data clear flags
Note: I encapsulate my coding efforts into one or more c++ classes. In my code, the ss objects are declared as a data attribute of my class, and thus accessible to all function attributes of that class, including each test_funci (i.e. no need to pass the ss)
I know that there is a lot of topics about overloading << operator, but it seems to always be used in class in order to make it support << operator. Hope I would not be duplicate
What I want to do is (I think) quite different (and probably simpler).
I have a console app with 2 threads, both writing on console. I want to avoid them from smashing to each other in the console, so I use a mutex to prevent a thread from outputing when the other one is, so i've created the function :
void print(string s){
globals::console_mtx.lock();
cout << s << endl;
globals::console_mtx.unlock();
}
I would like it to be usable like this, regardless of the data type :
int i=5;
print << "Some text" << i << endl;
Is << overloading what I need ? what would be the simplest way to achieve it ?
Thanks
Is this what you're thinking about?:
struct print_t {};
static const print_t print = print_t();
print_t& operator<<(print_t& p, const std::string& s) {
globals::console_mtx.lock();
std::cout << s << endl;
globals::console_mtx.unlock();
return p;
}
NB. there are about a dozen ways to make it better, like having print as a function with unique type, etc. to make sure you don't run into static (de)initialization order fiasco (avoid the above in static deinitialization if possible). You might use the definition of cout in std as a cheat sheet.
The problem with just overloading << is that:
print << "Some text" << i << endl;
Actually calls print.operator<<() separately for "Some text", i, and endl (also you need to make sure to have overloads for int and endl). If you lock and unlock for each call, then another thread could get the lock before you are done with all 3 calls. If for instance thread 2 had
print << "Other text" << i+1 << endl;
Then you might end up with:
"Some TextOther Text65\n\n"
The simplest way to deal with it is to output to a stringstream first, and then use a normal print function to print the entire thing protected by a locked mutex:
stringstream ss;
ss <<"Some text" << i << endl;
print(ss.str());
If you insist on using streams directly, then streams handle this kind of thing by only actually writing when it receives an instruction to flush. endl automatically flushes the stream, which is one of the ways it differs from "\n".
You then implement a custom std::stringbuf that locks the mutex and outputs to console on sync(), then you construct an ostream for each thread to use as its personal printing output stream.
Example code:
#include <iostream>
#include <sstream>
#include <mutex>
#include <thread>
#include <string>
// Increase risk of race condition if one can be triggered.
char slow_get_ch(char ch)
{
for (unsigned int i = 0; i < 10000; ++i)
{
for (unsigned int j = 0; j < 10000; ++j)
{
}
}
return ch;
}
class print_buf : public std::stringbuf
{
std::mutex& mtx_;
public:
print_buf(std::mutex& mtx)
:
mtx_(mtx)
{
}
protected:
int sync() final
{
std::unique_lock<std::mutex> lck(mtx_);
std::string val = this->str();
std::cout << val;
this->str("");
return 0;
}
};
void print_worker(std::ostream* print_stream_ptr,char ch)
{
std::ostream& print = *print_stream_ptr;
// Print 5 lines of 20 times ch.
for (unsigned int i = 0; i < 5; ++i) {
for (unsigned int j = 0; j < 20; ++j) {
print << slow_get_ch(ch);
}
print << std::endl;
}
}
int main()
{
std::mutex print_mutex;
print_buf buf1(print_mutex);
print_buf buf2(print_mutex);
print_buf buf3(print_mutex);
std::ostream p1(&buf1);
std::ostream p2(&buf2);
std::ostream p3(&buf3);
std::thread t1(print_worker, &p1, 'a');
std::thread t2(print_worker, &p2, 'b');
std::thread t3(print_worker, &p3, 'c');
t1.join();
t2.join();
t3.join();
return 0;
}
I'm trying to implement an output filter for logging and have modified some example code with unexpected results. The code is
#include <ctype.h> // toupper
#include <boost/iostreams/categories.hpp> // output_filter_tag
#include <boost/iostreams/operations.hpp> // put
#include <boost/iostreams/filtering_stream.hpp>
// cobbled from http://www.boost.org/doc/libs/1_48_0/libs/iostreams/doc/concepts/output_filter.html#examples
//
// g++ [-DTEST] -o t-pri t-pri.cpp
using namespace std;
namespace io = boost::iostreams;
int pri=4;
struct toupper_output_filter {
typedef char char_type;
typedef io::output_filter_tag category;
template<typename Sink>
bool put(Sink& snk, char c)
{
if(pri<3)
return io::put(snk, /* toupper((unsigned char) c)*/ c);
else
return 0;
}
};
int main(int argc, char**argv)
{
boost::iostreams::filtering_ostream out;
out.push(toupper_output_filter());
cout << "pri: " << pri << endl;
out.push(cout);
out << "test-1" << endl;
#ifdef TEST
pri=2;
out << "test-2" << endl;
#endif
return 0;
}
The unexpected behavior is encountered when the TEST macro is defined:
hbarta#itws007:~/Documents/C++/t-pri$ g++ -o t-pri t-pri.cpp
hbarta#itws007:~/Documents/C++/t-pri$ ./t-pri
pri: 4
hbarta#itws007:~/Documents/C++/t-pri$ g++ -DTEST -o t-pri t-pri.cpp
hbarta#itws007:~/Documents/C++/t-pri$ ./t-pri
pri: 4
test-1
test-2
hbarta#itws007:~/Documents/C++/t-pri$
It seems as if the expression 'if(pri<3)' is evaluated once when the structure member function is first being called. I expect it to be evaluated every time something is streamed to 'out.'
As an aside, I'm working toward something that logs to the console (or perhaps a file) and has the capability to filter based on bitmap. IOW, a mask would be defined and bits set in it to enable specific output statements to actually write something. Code could look like (where mask is anded with enable)
<sometype> mask(0x0101);
out << enable(0x0010) << "log message" << endl; // not output
out << enable(0x0100) << "another log message" << endl; // is output
This seems like a common sort of thing that a developer might want to do but I am unable to find an example to copy. I'm working toward a solution and ran into this.
Thanks!
Edit: Trying to add to the solution per Nikita's suggestion by adding the setPri class to use as an iomanip with an argument. Still not working as expected All output is cached until the program exits and then the last setPri() insertion takes effect. Is that how Boost iostreams should work?
#include <boost/iostreams/categories.hpp> // output_filter_tag
#include <boost/iostreams/operations.hpp> // put
#include <boost/iostreams/filtering_stream.hpp>
using namespace std;
namespace io = boost::iostreams;
// cobbled from http://www.boost.org/doc/libs/1_48_0/libs/iostreams/doc/concepts/output_filter.html#examples
//
// g++ -o to_upper to_upper.cpp
//
// Adding an iomanip with argument as in
// http://stackoverflow.com/questions/20792101/how-to-store-formatting-settings-with-an-iostream
// don't really want file scope variables...
static int pri=0; // value for a message
static int mask=1; // mask for enabled output (if pri&mask => output)
static int priIDX() { // find index for storing priority choice
static int rc = ios_base::xalloc();
return rc;
}
class setPri // Store priority in stream (but how to retrieve when needed?)
{
size_t _n;
public:
explicit setPri(size_t n): _n(n) {}
size_t getn() const {return _n;}
friend ostream& operator<<(ostream& os, const setPri& obj)
{
size_t n = obj.getn();
pri = n;
os << "setPri(" << n << ")"; // indicate update
return os;
}
};
struct toupper_output_filter {
typedef char char_type;
typedef io::output_filter_tag category;
template<typename Sink>
bool put(Sink& snk, char c)
{
if(pri & mask) // Should this char be sent to output?
return io::put(snk, c);
else
return 0;
}
};
int main(int argc, char**argv)
{
boost::iostreams::filtering_ostream out;
out.push(toupper_output_filter());
out.push(cout);
out << setPri(1) << " test-1" << endl;
out << setPri(2) << " test-2" << endl;
out << setPri(3) << " test-3" << endl;
return 0;
}
result is
setPri(1) test-1
setPri(2) test-2
setPri(3) test-3
The problem here is that toupper_output_filter applied to the output sequence after the pri variable changed to 2.
Statement out << "test-1" << endl; doesn't filter the sequence, it puts symbols into the buffer for the further procession. After that pri=2; and more symbols goes to the buffer at out << "test-2" << endl;. Before leaving the scope out filters it's buffer and outputs final symbols sequence. At this point pri is 2 and all the lines printed.
To fix the issue you could remove global state:
struct toupper_output_filter {
typedef char char_type;
typedef io::output_filter_tag category;
int pri;
toupper_output_filter (int logLevel)
{
pri = logLevel;
}
template<typename Sink>
bool put(Sink& snk, char c)
{
if(pri<3)
return io::put(snk, /* toupper((unsigned char) c)*/ c);
else
return 0;
}
};
And use it:
int main(int argc, char**argv)
{
boost::iostreams::filtering_ostream out;
int pri = 4;
out.push(toupper_output_filter(pri));
cout << "pri: " << pri << endl;
out.push(cout);
out << "test-1" << endl;
out.pop();
out.pop();
#ifdef TEST
pri=2;
out.push(toupper_output_filter(pri));
out.push(cout);
out << "test-2" << endl;
#endif
return 0;
}
Update:
The main idea of setPri class is to remove the static state and to manipulate priority with operator<<.
Draft for the solution:
static int mask=1; // mask for enabled output (if pri&mask => output)
struct toupper_output_filter {
typedef char char_type;
struct category : boost::iostreams::output_filter_tag {};
int pri;
toupper_output_filter(int n)
{
pri = n;
}
template<typename Sink>
bool put(Sink& snk, char c)
{
if(pri & mask) // Should this char be sent to output?
return io::put(snk, c);
else
return 0;
}
};
class setPri // Store priority in stream (but how to retrieve when needed?)
{
size_t _n;
public:
explicit setPri(size_t n): _n(n) {}
size_t getn() const {return _n;}
friend boost::iostreams::filtering_ostream& operator<<(boost::iostreams::filtering_ostream& out, const setPri& obj)
{
if (!out.empty())
{
out.pop();
out.pop();
}
out.push(toupper_output_filter(obj.getn()));
out.push(cout);
return out;
}
};
int main(int argc, char**argv)
{
boost::iostreams::filtering_ostream out;
out << setPri(1) << " test-1" << endl;
out << setPri(2) << " test-2" << endl;
out << setPri(3) << " test-3" << endl;
return 0;
}
Output is:
test-1
test-3
There are sooo many posts about converting from int to string but they all really involve either just printing to the screen, or using ostringstream.
I was using ostringstream, but my company doesnt want me to use any streams because it has horrid runtimes.
I was doing this in a C++ file.
my issue is that i was going to, over the course of execution create millions of streams, write to the buffers, and then copy content into a string, as such:
ostringstream OS;
os << "TROLOLOLOLOL";
std::string myStr = os.str();
There is redundancy as it is making this buffer then copying it all over. UGH!
In C++11:
string s = std::to_string(42);
I did a benchmark a couple of weeks ago, and got those results (using clang and libc++ shipped with current Xcode):
stringstream took 446ms
to_string took 203ms
c style took 170ms
With the following code:
#include <iostream>
#include <chrono>
#include <sstream>
#include <stdlib.h>
using namespace std;
struct Measure {
chrono::time_point<chrono::system_clock> _start;
string _name;
Measure(const string& name) : _name(name) {
_start = chrono::system_clock::now();
}
~Measure() {
cout << _name << " took " << chrono::duration_cast<chrono::milliseconds>(chrono::system_clock::now() - _start).count() << "ms" << endl;
}
};
int main(int argc, const char * argv[]) {
int n = 1000000;
{
Measure m("stringstream");
for (int i = 0; i < n; ++i) {
stringstream ss;
ss << i;
string s = ss.str();
}
}
{
Measure m("to_string");
for (int i = 0; i < n; ++i) {
string s = to_string(i);
}
}
{
Measure m("c style");
for (int i = 0; i < n; ++i) {
char buff[50];
snprintf(buff, 49, "%d", i);
string s(buff);
}
}
return 0;
}
In C++11 you have std::to_string. Although it probably uses the stringstream technique under the hoods.
You should take a look at the performance chart of boost::lexical_cast:
http://www.boost.org/doc/libs/1_52_0/doc/html/boost_lexical_cast/performance.html
It compares lexical_cast to stringstream (with and without construction) and scanf/printf.
In most cases boost::lexical_cast is faster than scanf, printf, std::stringstream.
Reusing the stringstream buffer. Note, this is not thread safe.
#include <sstream>
#include <iostream>
#include <string>
template<class T>
bool str_to_type(const char *str, T &value) {
static std::stringstream strm;
if ( str ) {
strm << std::ends;
strm.clear();
strm.setf(std::ios::boolalpha);
strm.seekp(0);
strm.seekg(0);
strm << str << std::ends;
strm >> value;
return !strm.fail();
}
return false;
}
int main(int argc, char *argv[])
{
int i;
if (!str_to_type("42", i))
std::cout << "Error" << std::endl;
std::cout << i << std::endl;
return 0;
}