简体   繁体   中英

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 (eg 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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM