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!
Related
How can I format my output in C++? In other words, what is the C++ equivalent to the use of printf like this:
printf("%05d", zipCode);
I know I could just use printf in C++, but I would prefer the output operator <<.
Would you just use the following?
std::cout << "ZIP code: " << sprintf("%05d", zipCode) << std::endl;
This will do the trick, at least for non-negative numbers(a) such as the ZIP codes(b) mentioned in your question.
#include <iostream>
#include <iomanip>
using namespace std;
cout << setw(5) << setfill('0') << zipCode << endl;
// or use this if you don't like 'using namespace std;'
std::cout << std::setw(5) << std::setfill('0') << zipCode << std::endl;
The most common IO manipulators that control padding are:
std::setw(width) sets the width of the field.
std::setfill(fillchar) sets the fill character.
std::setiosflags(align) sets the alignment, where align is ios::left or ios::right.
And just on your preference for using <<, I'd strongly suggest you look into the fmt library (see https://github.com/fmtlib/fmt). This has been a great addition to our toolkit for formatting stuff and is much nicer than massively length stream pipelines, allowing you to do things like:
cout << fmt::format("{:05d}", zipCode);
And it's currently being targeted by LEWG toward C++20 as well, meaning it will hopefully be a base part of the language at that point (or almost certainly later if it doesn't quite sneak in).
(a) If you do need to handle negative numbers, you can use std::internal as follows:
cout << internal << setw(5) << setfill('0') << zipCode << endl;
This places the fill character between the sign and the magnitude.
(b) This ("all ZIP codes are non-negative") is an assumption on my part but a reasonably safe one, I'd warrant :-)
Use the setw and setfill calls:
std::cout << std::setw(5) << std::setfill('0') << zipCode << std::endl;
In C++20 you'll be able to do:
std::cout << std::format("{:05}", zipCode);
In the meantime you can use the {fmt} library, std::format is based on.
Disclaimer: I'm the author of {fmt} and C++20 std::format.
cout << setw(4) << setfill('0') << n << endl;
from:
http://www.fredosaurus.com/notes-cpp/io/omanipulators.html
or,
char t[32];
sprintf_s(t, "%05d", 1);
will output 00001 as the OP already wanted to do
Simple answer but it works!
ostream &operator<<(ostream &os, const Clock &c){
// format the output - if single digit, then needs to be padded with a 0
int hours = c.getHour();
// if hour is 1 digit, then pad with a 0, otherwise just print the hour
(hours < 10) ? os << '0' << hours : os << hours;
return os; // return the stream
}
I'm using a ternary operator but it can be translated into an if/else statement as follows
if(c.hour < 10){
os << '0' << hours;
}
else{
os << hours;
}
Many warning messages (via std::cout) might be printed out during the process. Is there a way to postpone the printing of the warning messaged in the end of the program? There are huge amount of the processing information will be printed. I'm planing to have all the warnings together in the end rather than scattered around.
More background:
code is already there.
there are about 50 warning messages within the code (in case if there is some sort of delay( ) function, I don't want to add 50 times, would be nice if there is an globally delaye/postpone function for stand output)
Thanks
One way to do it is to send everything to a stringstream, and then print at the end.
For example:
#include <iostream>
#include <sstream>
int main(){
int i = 5, j = 4;
std::stringstream ss;
std::cout << i * j << std::endl;
ss << "success" << std::endl;
std::cout << j + i * i + j << std::endl;
ss << "failure" << std::endl;
std::cout << ss.str() << std::endl;
return 0;
}
Output:
20
33
success
failure
If you're just trying to delay all printing of std::cout what you can do is redirect standard out to a string stream that acts as a buffer. It's pretty simple and avoids all of the dup, dup2, and piping stuff that one might be inclined to try.
#include <sstream>
// Make a buffer for all of your output
std::stringstream buffer;
// Copy std::cout since we're going to replace it temporarily
std::streambuf normal_cout = std::cout.rdbuf();
// Replace std::cout with your bufffer
std::cout.rdbuf(buffer.rdbuf());
// Now your program runs and does its thing writing to std::cout
std::cout << "Additional errors or details" << std::endl;
// Now restore std::cout
std::cout.rdbuf(normal_cout);
// Print the stuff you buffered
std::cout << buffer.str() << std::endl;
Also in the future, you should really use a buffer for errors from the start OR at a minimum write errors and logging to std::cerr so that your normal runtime print outs aren't cluttered with errors.
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.
I had a segmentation fault in my code, so I put many cout on the suspicious method to localise where.
bool WybierajacyRobot::ustalPoczatekSortowania(){
cout << "ustal poczatek sortowania: " << poczatekSortowania << endl ;
list< Pojemnik >::iterator tmp;
cout << "LOL"; // <-- this cout doesn't print when segfault
if (!poczatekSortowania){ // <- T1
cout << "first task" ;
tmp = polka.begin();
}
else{ // <-- T2
cout << " second task " ;// <-- this cout doesn't print when segfault
tmp = ostatnioUlozony;
cout << " debug cout " ; // <-- this cout doesn't print when segfault
++tmp; // <-- segfault
} ...
If the method was call and don't have segfault every cout from T1 and before was printed.
In line ++tmp is segfault because ostatnioUlozony is NULL, when method go to T2 every cout without first wasn't printed. Why?
I'm using Netbeans ang gcc, I found the "segfault line" with debug in Netbeans, but before I use then I spend some time on adding cout line and running program.
Thanks a lot,
You need to flush the output stream with either std::flush or std::endl (which will give a newline as well), otherwise you are not guaranteed to see the output:
cout << " second task " << std::flush;
Nonetheless, you have undefined behaviour if you increment a singular iterator (which the null pointer is), so this is only likely to work. As far as C++ is concerned, your program could launch a nuclear missile instead.
Another solution is to use std::cerr instead of std::cout. It is unbuffered, so no flushing is required, and it's slightly more idiomatic to use std::cerr for debugging purposes.
I want to calculate time of a loop that it takes to finish.
I do something like:
ptime before = second_clock::local_time(); //get current time
cout << "Started: "<< before << " ... processing ...";
while(foo) {
....
}
ptime after = second_clock::local_time(); // get Current time
cout << "Processing took" << after - before;
This will output: Started: "some time"
then I wait for the loop to finish before I get to see " ... processing ..."
Why is that? It should first cout the whole text and then go into the loop.
If I change the first cout to:
cout << "Started: "<< before;
It doesn't even show me the time before the loop finishes.
That's the most weird thing I've ever seen...seems there's something going wrong with my understanding of boost time.
I'm using boost::threads too in my code but workers are spwaned within the loop so I don't see how this could have to do with this problem.
Can someone help me out here?
ostreams including cout use buffers, which means the implementation can wait to see if you will send more data before actually acting on it.
To get cout to print sooner, use
std::cout << std::flush;
or use std::endl, which is equivalent to "\n" followed by std::flush.