something weird is happening to my program. I am currently using lots of threads in my program, and will not be feasible to paste everything here.
However this is my problem:
int value = 1000;
std::cout << value << std::endl;
//output: 3e8
Any idea why is my output 3e8?
Whats the command to fix it back to print decimal values?
Thanks in advance! :)
Some other thread changed the default output radix of the std::cout stream to hexadecimal. Note that 100010 = 3e816, i.e. 1000 == 0x3e8.
Somewhere in your program a call such as:
std::cout << std::hex << value;
has been used. To revert output to normal (decimal) use:
std::cout << std::dec;
here is a relevent link to the different ways numbers can be output on std::cout.
Also, as pointed out in the comments below, the standard method of modifying cout flags safely appears to be the following:
ios::fmtflags cout_flag_backup(cout.flags()); // store the current cout flags
cout.flags ( ios::hex ); // change the flags to what you want
cout.flags(cout_flag_backup); // restore cout to its original state
Link to IO base flags
As stated in the comments below, it would also be wise to point out that when using IO Streams it is a good idea to have some form of synchronisation between the threads and the streams, that is, make sure no two threads can use the same stream at one time.
Doing this will probably also centralise your stream calls, meaning that it will be far easier to debug something such as this in the future.
Heres an SO question that may help you
Chances are that another thread has changed the output to hex on cout. I doubt that these streams are thread-safe.
Related
I want to thousand-separate numbers (e.g. 6,000,000). After doing some research I wrote the below method:
template<class TYPE>
std::string thousands(const TYPE num)
{
std::ostringstream ss;
ss.imbue(std::locale(""));
ss << value;
return ss.str();
}
To be used like:
std::cout << thousands<uint64_t>(value) << std::endl;
Initially this seemed to work in a single threaded environment. However, I have started using multiple threads and even though I am passing in a stack variable (not shared across threads) the value of num was getting incremented by the formatting. When I removed the formatting the incrementing stopped.
Is there some oddity with using the above technique to format strings from multiple threads?
After some more testing, does imbue cache anything? The problem seems to trigger when both threads call it at the same time.
UPDATE
Whilst testing I was able to safely conclude the above code is definitely causing problems and some sort of caching/static is occurring. When I replace the above with return std::to_string(num) the problem never occurs. I revert back to the above code, problem occurs every time. I use one thread- no problem. Two threads calling imbue(), problem reappears.
Using Clang compiler, CentOS 7 OS.
Windows cout and printf is really slow, so when a lot of data is sent it slows applications (it happens with code running during days to check if all is working well).
A metod to make it faster is to use a buffer by writting following code at the beginning of the main() function:
#ifndef __linux__ //Introduce this code at the beginning of main() to increase a lot the speed of cout in windows:
char buffer_setvbuf[1024];setvbuf(stdout, buffer_setvbuf, _IOFBF, sizeof buffer_setvbuf); //¿¡¡Sometimes it does not print cout inside a function until cout is used in main() or end of buffer is reached.
#endif
But unfortunately a side effect is that sometimes it does not print the data because the buffer is not full.
Then the questions:
1. How to force print: by making \n?
2. How to disable the buffer?
printf
I see you are trying to use larger buffer on memory to reduce the number of writes on stdout. Indeed, your code would not print anything until your buffer becomes full, because the buffering mode is set to _IOFBF (i.e. full buffering). Since you want control when to flush, there are two ways to go about.
Use _IOLBF (i.e. line buffering), and put newline character whenever you want to flush.
Call fflush(stdout) to manually flush the buffer.
std::cout
I think std::cout should be preferred when writing c++ code, because of its ease of use. One thing that might slow down the I/O process is synchronization between iostream and stdio. As far as I know, the default on many systems is to keep the two in sync, and it has some overhead. You can disable it by calling std::ios_base::sync_with_stdio(false). reference
When you need to flush output, you can use what is called "manipulators" for output stream - namely std::flush and std::endl. When those manipulators are put into an output stream like the following: std::cout << "your string" << std::endl, it is guaranteed that the output stream is flushed.
std::endl reference
std::flush reference
Bottom Line
Use fflush to flush stdout when using printf for output.
I recommend trying std::cout with sync off, and test if it fits your performance need.
Alright, I have a programming challenge due but unfortunately, although my code does in theory, doesn't work so I was wondering if it was a compiler issue (I use Code::Blocks) or if its something I'm not seeing. Any help would be appreciated, Thanks!
Here's my code:
#include <iostream>
#include <string>
#include <math.h>
using namespace std;
int main(){
double sliceStore, sliceSize = 14.125, totalSlice, area;
cout << "How Many Slices?" << endl;
//getline(cin,sliceStore);
cin >> sliceStore >> endl;
return 0;
}
Remove "endl" from the input statement !!
The complete error message for this is not nice and goes on for a few pages, but code::blocks usually fronts GCC and g++, GCC's C++ compiler, should have started the message of with something like this:
cin >> sliceStore >> endl;
^
In English, the compiler could not find a way for the >> operator to put data into endl. A bit of reading up on what endl is may have solved your problem. endl is a function, not a variable.
ostream& endl(ostream&)
Crack your textbook and read up on input and output streams.
cin is the name of an input stream attached to the main console, usually represented by the command prompt. Input streams use >>, which is also a function, one that usually looks like
istream& operator>>(istream&, somedatatype&)
So cin >> endl; really looks like is a function call something like
cin = operator>>(cin, endl());
However, no one has built an operator>> with a somedatatype that looks like ostream& endl(ostream&) and the compiler prints out a huge list of operator>> possibilities that look something like it as a hint of what you might have meant to do.
Most of the time this is helpful. Most functions only have a couple overloads, and you can quickly see what you did wrong. But operator>> has an overload for every common datatype and dozens of not so common data types. Blah.
Onto what the endl function does.
It tells an output stream to do two things: to end the line and to flush the output buffer.
Ending the line's pretty simple, the only caveat is everybody seems to do it differently so if you compile the same program under different operating systems you'll get slightly different output.
The output buffer flush is a instruction to the output stream to send any data it's been holding onto, buffering, for a good chance to send it.You generally want to send stuff in chunks because it's more efficient. Say you want to write to a file. In the world of a computer where things happen in nanoseconds, writing to a file can take seconds. For example, the hard disk could be in a low power sleep state and have to start spinning. Then it has to find where the file goes on the hard drive. Then it has to wait for the hard drive to spin into the right position. You don't want to go through all that just to write one character as each time you press a key on the keyboard, so the computer builds up a bunch of writes in memory--the buffer--thee writes the contents of the buffer after it fills up, hasn't been added to for a while, or is forced to with a flush instruction. endl provides that flush. As a result, overuse of endl can slow down your program.
#include <iostream>
using namespace std;
int main()
{
cout << 1;
while (true);
return 0;
}
I thought that this program should print 1 and then hung. But it doesn't print anything, it just hungs.
cout << endl or cout.flush() can solve this problem, but I still want to know why it's not working as expected :)
This problem appeared during codeforces contest and I spent a lot of time on looking at strange behavior of my program. It was incorrect, it also hunged, hidden output was actually debug information.
I tried using printf (compiling with gcc) and it behaves as well as cout, so this question can be referred to C also.
You writing to a buffer. You need to flush the buffer. As #Guvante mentioned, use cout.flush() or fflush(stdout) for printf.
Update:
Looks like fflush actually works with cout. But don't do that - it may not be the fact in all cases.
That is because cout buffers output. You have to flush the buffer for it to actually print.
endl and flush() both perform this flushing.
Also note that your program hangs because you have an infinite loop (while(true);).
The reason it does this is so that if you are printing a lot of data (say 1000 numbers) it can do so drastically more efficiently. Additionally most minor data points end with endl anyway, since you want your output to span multiple lines.
Concerning printf, the same as cout holds: you're printing into a buffer, you need to flush it with fflush(stdout);. Termination will flush the buffer, this is why you can see the output without your infinite loop.
See Why does printf not flush after the call unless a newline is in the format string? for more information.
Ok, I'm working on my Operating Systems assignment. I need to write a microkernel which is able to do some basic stuff with threads, semaphores, events, etc.
BCC 3.1 is imitating my system environment. Classical debugging is really not of use. I'm debugging in cout style.
Problem is weird behavior of cout. It writes out in blocks or something. If I do, like, 40 couts it writes everything out. If I do 39 of them, it doesn't write any of them. On other hand if i do between 40 and 79 couts, it still writes only first 40, but if I do 80 of them, they're all ok, etc. Numbers are not exact, I'm not sure what's the number really. But I have also noticed that changing the length of string that is cout-ed effects the same way. Only I don't know how many characters equals one cout call.
Additional information available upon request. Thanks in forward.
sounds like buffering regardless of the fact std::cout shouldn't buffer output. in any case you can try flushing cout by
std::cout.flush();
or
std::cout << std::flush;
or
std::cout << std::endl;
or even by disabling buffering:
std::cout.rdbuf()->pubsetbuf(0, 0);