fstream behaving weirdly - c++

I am new to c++, but this is ridiculous!
// fstream output;
// string func();
// both have proven to be working somewhat properly, as I got something already
// written correctly in the output file and I tested func() in the cout
output << func(); // func() returns a string;
And I get written in the file:
// literally nothing
But when I do
output << "what the hell" << endl;
output << func();
I get
what the hell
{// expected output}
what the hell
{// expected output}
...
what the hell
// last output still missing
I got no idea of what might be the problem, at this point I am convinced the program is just doing it to spite me.
EDIT:
string func()
{
return "test\n";
}
I also just found out that as long as I manually put something to the output in the end, everything will be written, like this:
for(int=0; i<4; i++)
{
output << func();
}
output << endl;
get me
test
test
test
test
// func line
// endl line

As One Man Monkey Squad commented, it was just a problem of not flushing the fstream.
string func()
{
return "test"
}
output << func() << endl;
get me the desired output, without a extra line at the end, beyond the normal new line

Related

No output from cout When assertion Fails

Cout fails to print anything even though it is on a line before the assertion. It behaves so when I compile and run the code through linux shell. But it prints when tried with an online compiler.
ex-
for(int i =0;i<n;i++)
{ std::cout << "should print";
assert(2==1);
}
I should see "should print" at least once right? And why the different behaviour through online compilers?
Output from std::cout is probably being buffered here. Explicitly emptying the buffer should make it print before the assertion fails. (std::endl,std::flush, std::unitbuf manipulators should do)
for(int i =0;i<n;i++)
{ std::cout << "should print" << std::endl;
assert(2==1);
}

How to prevent clang-format from adding newlines between stream operator calls <<

We are currently in the process of formatting our code base with clang-format. We found a situation where for some reason the stream operator to std::cout is moved to the next line if two consecutive strings literals are present. Putting a variable in between thw two string literals causes clang-format to not change the format. What needs to be changed in the .clang-format file to avoid this?
int main()
{
std::cout << "something" << "something" << std::endl;
}
becomes
int main()
{
std::cout << "something"
<< "something" << std::endl;
}
while
int main()
{
int a = 0;
std::cout << "something" << a << "something" << std::endl;
}
stays untouched.
Note while this last snippet is wider, it is not split across multiple lines, while the shorter snippet above is.
This is with LLVM 9.0.0 Windows installer and is reproducible with the default config file.
This behavior can't be altered via the .clang-format file, as it is part of the code.
This behavior was introduced in this commit:
https://github.com/llvm-mirror/clang/commit/df28f7b8dd6a032515109de4ff5b4067be95da8e
Link to bug report: https://bugs.llvm.org/show_bug.cgi?id=45018

Why is my first ofstream output in my else block missing the fill character?

I'm using this code to output nodes of a huffman tree to a text file with a certain formatting. All the node outputs within the if block run as expected, but the first output in the else block is missing the '0' fill character after the "L:". It should output "L:076" but instead is outputting "L: 76". The cout looks correct but the text file isn't. All future loops through the else block output like they should, it's only the first loop that is missing the fill character. Here's a picture of my output
void preOrder(node* tree, std::ofstream& of) {
if (tree->label > 0) {
of << "I:" << tree->label << " ";
}
else {
std::cout.width(3);
std::cout << std::right;
std::cout.fill('0');
std::cout << int(tree->ch) << std::endl;
of << "L:";
of << of.fill('0');
of << std::right;
of << int(tree->ch);
of << " ";
return;
}
preOrder(tree->left, of);
preOrder(tree->right, of);
}
From cppreference.com:
The second form (2) sets fillch as the new fill character and returns the fill character used before the call.
"The second form" is the non-const version, that applies here. So my guess (I never used fill myself and I cannot compile your code as it is) would be that the call is correctly applied and then you put the old fill character (blank space presumably) to the stream, because you do:
of << of.fill('0');
Also, I noticed that you dont set the width of of.
Because you're hiding something naughty from us.
#include <iostream>
int main()
{
std::cout.width(3);
std::cout << std::right;
std::cout.fill('0');
std::cout << 3 << std::endl;
return 0;
}
Outputs 003 (live example).
Please provide an MCVE and I'll edit my answer to help you.

Printing a NumericUpDown value out of a ofstream

This should be a simple task, but I am recieving a file containing the number "1" instead of the contents of the numericUpDown control. Using breakpoints I can see the value from
ta[i]->Value is the value I would expect it to be, but then after the conversion I get a 1 in the file instead of the value.
private: void storePreviousSettings()
{
ofstream settings("prev_settings.txt");
if(settings.is_open())
{
settings << "#ta" << endl;
for(int i = 0; i < 16; i++)
{
settings << ta[i]->Value.ToString() << endl;
}
settings << "End" << endl;
settings.close();
}
}
Note: ta is defined like so:
private: NumericUpDown * ta[];
Why am I printing a "1" to the file with the ofstream instead of the value in the numericUpDown component? How can I fix this? Is there an alternative method for writing to a file can I perform?
Update/Current Failed Attempts
If I add this line:
System::String * temp = ta[i]->Value.ToString();
Before the "settings << ta[i]->Value ..." line, using break points I can see that "temp" holds the expected value, and ta[i]->Value.ToString() is working. So when ta[i]->Value.ToString() is used with the << operator something must be changing in order for me to recieve a "1" in the file instead of the value I am seeing at my break points before it is wrote to the file.
Any help or direction is appreciated. Thanks.
The problem has been solved using the following conversion on the Decimal to make it a double.
private: void storePreviousSettings()
{
ofstream settings("prev_settings.txt");
if(settings.is_open())
{
settings << "#ta" << endl;
for(int i = 0; i < 16; i++)
{
settings << System::Decimal::ToDouble(ta[i]->Value) << endl;
}
settings << "End" << endl;
settings.close();
}
}
If anyone knows the reason why using .ToString() did not work originally, please post. I am answering this in hopes that it might aid someone else in the same situation.

cout no output but printf does

I'm very new to programming in C++ but I'm trying to write some code which filters a specific word from a string and then takes a specific action. For some reason the code does not see the text inside the string.
printf("%s \n", data.c_str());
cout << data;
This shows absolutely nothing - meaning I cannot use .find or write it to a file.
printf("%s \n", data);
This shows exactly what I need.
I am writing the code into data with assembly:
mov data, EDX
Why is that I can only use the the last method?
Edit:
Data is initiated as:
std::string data;
If a pointer to a string is null all subsequent calls to cout
stop working
const char* s=0;
cout << "shown on cout\n";
cout << "not shown" << s << "not shown either\n";
cout << "by bye cout, not shown\n";
The two function calls are not equivalent, as \n at printf flushes the stream. Try with:
cout << data << endl;
Be sure you used
#include <string>
in your file header. With this in place you should be able to use
std::cout << data << endl;
with no issues. If you're using a global namespace for std you may not need the std::, but I'd put it anyway to help you debug a it faster and eliminate that as a possible problem.
In Short
You will have a problem with cout, if you don't put a linebreak at it's end!
In Detail
Try adding an endl to your cout (e.g. std::cout << data << std::endl), or use following instruction to activate "immediate output" for cout (without it needing a linebreak first).
std::cout << std::unitbuf;
Complete example:
std::cout << std::unitbuf;
std::cout << data;
// ... a lot of code later ...
std::cout << "it still works";
Sidenote: this has to do with output buffering, as the name unitbuf suggests (if you want to look up what is really happening here).
This way it is also possible to rewrite the current line, which is a good example, where you would need this ;-)
Practical example
using namespace std;
cout << "I'm about to calculate some great stuff!" << endl;
cout << unitbuf;
for (int x=0; x<=100; x++)
{
cout << "\r" << x << " percent finished!";
// Calculate great stuff here
// ...
sleep(100); // or just pretend, and rest a little ;-)
}
cout << endl << "Finished calculating awesome stuff!" << endl;
Remarks:
\r (carriage return) puts the curser to the first position of the line (without linebreaking)
If you write shorter text in a previously written line, make sure you overwrite it with space chars at the end
Output somewhere in the process:
I'm about to calculate some great stuff!
45 percent finished!
.. and some time later:
I'm about to calculate some great stuff!
100 percent finished!
Finished calculating awesome stuff!