简体   繁体   中英

cout partially print without endl

I'm printing a bunch of strings as following:

cout<<count<<"|"<<newTime.time<<"|"<<newCat<<"|"<<newCon<<endl;

in which count is a counter, newTime.time is a string of time, and newCat and newCon are both strings. The output is like following:

06:02:11:20:08|DB Mgr|Sending query: “SELECT * FROM users” 

Apparently, it left out the count and "|". However, if I change the code into

cout<<count<<"|"<<endl;
cout<<newTime.time<<"|"<<newCat<<"|"<<newCon<<endl;

The output just turned into

2|
06:02:11:20:08|DB Mgr|Sending query: “SELECT * FROM users” 

I was first thinking if this is the problem of buffer. I changed endl to flush but the problem still exists. Thanks for any help.

It sounds like your time string may have a carriage return \\r in it. If that's the case, then outputting using your first method will still output the count and separator, but the \\r will return to the start of the line and begin overwriting it.

Your second method will not overwrite the count since it's on the previous line (a \\r will have little visible effect if you're already at the start of the line).

If you're running on a UNIX-like platform, you can pipe the output through something like od -xcb (a hex dump filter) to see if there is a \\r in the output.

Alternatively, if you have a string in your code, you can see if it contains a carriage return with something like:

std::string s = "whatever";
size_t pos = s.find ('\r');
if (pos != std::string::npos) {
    // carriage return was found.
}

By way of example, the following program:

#include <iostream>

int main (void) {
    std::string s1 = "strA";
    std::string s2 = "\rstrB";
    std::string s3 = "strC";

    std::cout << s1 << '|' << s2 << '|' << s3 << '\n';
    std::cout << "=====\n";

    std::cout << s1 << '|' << '\n';
    std::cout << s2 << '|' << s3 << '\n';

    std::cout << "=====\n";
    size_t pos = s2.find ('\r');
    if (pos != std::string::npos)
        std::cout << "CR found at " << pos << '\n';
    return 0;
}

seems to output the following:

strB|strC
=====
strA|
strB|strC
=====
CR found at 0

but in fact that first line is actually:

strA|(\r)strB|strC

where (\\r) is the carriage return.


And keep in mind you rarely need endl - it's effectively a \\n with a flush which is not really necessary in most cases. You can just get away with using \\n and let the automated flushing take care of itself.

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