Use << operator with own function to "override" cout - c++

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;
}

Related

Capture a functions standard output and write it to a file

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)

Is there a possibility to use cin parallel to cout?

I'm trying to write a program in C++ which will be responsible for simulating blinkers in cars. I want it to be simple and to compile it in a console window.
Is it possible to create one thread for input which will be always active and second for output that will run simultaneously?
I wanted to use threads to solve this but it doesn't work as I would like. I have a little trouble to understand threads. If anyone could help me to fix this I would be grateful.
int in()
{
int i;
cout<<"press 1 for left blinker or 0 to turn it off: ";
cin>>i;
return i;
}
void leftBlinker()
{
int i;
cout << "<-";
Sleep(1000/3);
cout << " ";
Sleep(1000/3);
}
int main()
{
thread t1 (in);
if (in()==1)
{
for (int i=0; i<100; i++)
{
thread t2(leftBlinker);
if (in()==0)
break;
}
}
system("pause");
return 0;
}
Here is a simple example code:
#include <atomic>
#include <chrono>
#include <iostream>
#include <thread>
int in(std::atomic_int &i) {
while (true) {
std::cout << "press 1 for left blinker or 0 to turn it off: ";
int input;
std::cin >> input;
i = input;
}
}
void leftBlinker(std::atomic_int &i) {
while (true) {
if (i) {
std::cout << "<-" << std::endl;
std::this_thread::sleep_for(std::chrono::milliseconds{333});
std::cout << " " << std::endl;
std::this_thread::sleep_for(std::chrono::milliseconds{333});
}
}
}
int main() {
std::atomic_int i{0};
std::thread t1(in, std::ref(i));
std::thread t2(leftBlinker, std::ref(i));
t1.join();
t2.join();
return 0;
}
A reference to std::atomic_int is passed to both functions for communication. std::atomic_int ensures thread-safe reads and writes. At the end you should join or detach the threads.

cout with this_thread::sleep_for?

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;
}

How to add integers and strings in the same vector?

I need help for my university homework. i'm still new to this.
Basically i am doing a run-length encoding and i don't know how to add the letter after the counter:
#include <iostream>
#include <string>
#include <vector>
#include <stdexcept>
void error(std::string str)
{
throw std::runtime_error(str);
}
int main()
{ int counter = 1;
std::string id;
std::vector<int> v;
std::cout << "Enter the data to be compressed: ";
std::cin >> id;
try
{ for(int i = 0; i < id.size(); i++)
{
if(std::isdigit(id[i]))
error("invalid input");
}
std::cout << "The compressed data is: ";
for(int i = 0; i < id.size(); i++)
{
if(id[i] == id[i+1])
{
counter++;
}
else if(id[i]!= id[i+1])
{
v.push_back(counter);
v.push_back(id[i]);
counter=1;
}
}
for(int j = 0; j < v.size(); j++)
std::cout << v[j];
}
catch(std::runtime_error& str)
{
std::cerr << "error: " << str.what() << std::endl;
return 1;
}
return 0;
}
For example if i input aaabbb, the probram should output 3a3b. The problem is that it outputs 397398 97 and 98 being the ascii code for a and b.
i don't know how to put the letter after the counter and for them to be in the same vector.
If you want to serialize as a string try this :
#include <iostream>
#include <string>
#include <vector>
#include <stdexcept>
#include <sstream>
void error(std::string str) {
throw std::runtime_error(str);
}
int main() {
std::ostringstream stream;
int counter = 1;
std::string id;
std::cout << "Enter the data to be compressed: ";
std::cin >> id;
try {
for (int i = 0; i < id.size(); i++) {
if (std::isdigit(id[i]))
error("invalid input");
}
std::cout << "The compressed data is: ";
for (int i = 0; i < id.size(); i++) {
if (id[i] == id[i + 1]) {
counter++;
} else if (id[i] != id[i + 1]) {
stream << counter;
stream << (char) id[i];
counter = 1;
}
}
std::cout << stream.str() << std::endl;
} catch (std::runtime_error& str) {
std::cerr << "error: " << str.what() << std::endl;
return 1;
}
}
v[j] from std::cout << v[j] is of type int and that is why std::cout writes a number. To write it as a character, you should cast v[j] to char as follows: std::cout << (char)v[j]. In this way, std::cout will use the char specialization, not the int one.
While the other answers might give you the output you need, I believe the idiomatic way to solve this is using a class to hold both the character and its count. There are two obvious choices.
std::pair
Could also be std::tuple if you prefer it for consistency or whatever reason. Save your results in a std::vector<std::pair<char, int>. This saves the information, but to print it you would need to define an appropriate function. Add elements via
v.emplace_back(character, count);
Wrapper Class
If you want to offer some functionality without outside helper classes, define a custom wrapper class such as the following.
class CharacterCount {
private:
char character;
int count;
public:
CharacterCount(char character, int count):
character(character), count(count) {}
explicit operator std::string() const { return std::to_string(count) + character;
// Other helper functions or constructors you require
}
This simplifies printing
for (auto& character_count : v)
std::cout << static_cast<std::string>(character_count);
I believe because std::ostream::operator<< is templated, you cannot get an implicit conversion to std::string to work. I would advise against implicit conversion anyway.
You can use the same emplace_back syntax as before because we offer an appropriate constructor.
So you take your input in a string and ultimately just need to stream this information out, ultimately meaning there's really no reason to store the information in a vector, just output it! You can use find_if with a lambda to find the non-consecutive character (or find_if_not if you prefer.)
for(string::const_iterator finish, start = cbegin(id); start != cend(id); start = finish) {
finish = find_if(start, cend(id), [value = *start](const auto i) { return i != value; } );
cout << distance(start, finish) << *start;
}
Live Example

Object changing after storing and retrieving from unordered_map

Consider the following code. I want to use mutex_by_name() to create and retrieve mutexes. The lock is not a real lock, but should do its job with a one second gap.
Expected output is that m4.lock() fails aka prints lock FAILED because _locked is already set to true. But it does lock. I'm new to C++ and pretty sure I'm missing something obvious. Can you please explain how to implement that correctly.
#include <iostream>
#include <string>
#include <unordered_map>
#include <unistd.h>
class Mutex {
private:
int _id;
bool _locked = false;
void status(std::string s) {
std::cout << _id << " " << name << " " << s << " " << std::endl;
}
public:
const std::string name;
Mutex(std::string name): name(name) {
static int id = 0;
_id = id++;
status("created");
}
Mutex(const Mutex& m): _id(m._id), _locked(m._locked), name(m.name) {
status("copy-constructed");
}
Mutex(Mutex&& m) = delete;
void operator=(Mutex&) = delete;
~Mutex() {
status("deleted");
}
void lock() {
// YES, THIS IS NOT A REAL AND SAFE LOCK
if (!_locked) {
_locked = true;
status("locked");
} else {
status("lock FAILED");
}
}
};
std::unordered_map<std::string, Mutex> mutexe;
Mutex& mutex_by_name(std::string name) {
mutexe.emplace(name, Mutex(name));
auto found = mutexe.find(name);
return found->second;
}
using namespace std;
int main() {
cout << "# 1" << endl;
Mutex m1 = mutex_by_name("hello");
m1.lock();
sleep(1);
cout << "# 2" << endl;
Mutex m4 = mutex_by_name("hello");
m4.lock();
sleep(1);
}
You have to problems. First of all, you're not declaring m1 and m4 as references, and they shall be so.
Secondly, code style :).
So, this shall solve it:
Mutex &m1 = mutex_by_name("hello");
//...
Mutex &m4 = mutex_by_name("hello");
In main you need to make m1 and m4 references (Mutex &m1). Right now they are copies and thus aren't updating the value in the unordered map.