C ++:如何在不回车的情况下打印新行 [英] c++: how to print new line without carriage return

查看:53
本文介绍了C ++:如何在不回车的情况下打印新行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
如何使cout表现为二进制模式?

我正在使用C ++将二进制数据打印到标准输出,然后将其重定向到文件.(我不想直接写入文件).但是,当我尝试打印值'0A'时,我得到的是'0D 0A'.(这是将输出复制到HexEdit时看到的).据我所知,'0A'是'new line'的ascii,因此cout自动添加'carriage return'.我想要的是单独打印 0A .我该怎么办?

I am using C++ to print binary data to the stdout and then I redirect it to a file. (I do not want to write directly to a file). However, when I try to print the value '0A' I am getting '0D 0A'. (this is what I see when I copy the output to HexEdit). From what I can figure out, '0A' is the ascii for 'new line' so cout automatically adds the '0D' which is 'carriage return'. What I want is to print 0A alone. how can I do this?

我的代码:

unsigned char *buf = new unsigned char[width+1];
for (int x = 0; x < width; x++) 
{
    buf[x] = (unsigned char) src[x];
}
buf[width] = '\0'
cout<<buf; 

我已经看到了:

I've seen this: Print new line to a text file without carriage return (CR) in windows but it does not seem to help me.

推荐答案

您无法使用任何标准输出流或文件来控制行序列的结尾.解决此问题的唯一方法是对标准输出 stdout 进行 freopen(),打开方式为 wb 或wb +`,以控制基础格式,例如:

You can't control the end of line sequence with any of the standard output streams or files. The only way to deal with this is to freopen() the standard output stdout with an open mode of wb or wb+` to control the underlying formatting, e.g.:

FILE* out = freopen("stdout.txt", "wb", stdout);
std::cout << "hello, world\n";

如果仅使用C ++流,还可以用适当打开的 std :: ofstream 的流缓冲区替换 std :: cout 的流缓冲区.:

If you are only using C++ streams you can also replace std::cout's stream buffer with the stream buffer of an appropriately opened std::ofstream, e.g.:

std::ofstream   file("stdout.txt", std::ios_base::out);
std::streambuf* coutbuf = std::cout.rdbuf(file.rdbuf());
std::cout << "hello, world\n";
...
std::cout.rdbuf(coutbuf);

您需要恢复原始流缓冲区,以避免在销毁期间使用 std :: cout 出现问题:至少在 main()已退出.如果您可以接受内存泄漏,则可以直接使用动态分配的 std :: filebuf .

You need to restore the original stream buffer to avoid problems with uses of std::cout during destruction: at the very least the stream gets flushed at some point after main() is exited. If you can accept a memory leak, you can use a dynamically allocated std::filebuf directly.

以上解决方案均未将输出实际写入标准输出,而是全部写入文件.我不知道如何在Windows系统上重新打开标准输出(在UNIX系统上,您可以使用文件描述符 1 创建流缓冲区,但是在UNIX上则完全没有必要,因为 \ n 不会被替换掉).特别是,可能无法重新打开流以适应输出重定向.

None of the solutions above actually writes the output to the standard output, they all write to a file. I don't know how to reopen the standard output on a Windows system (on a UNIX system you'd either create a stream buffer using file descriptor 1 but on UNIX there is no need anyway because the \n doesn't get replaced in the first place). In particular, reopening the stream to fit in with output redirection is probably not possible.

这篇关于C ++:如何在不回车的情况下打印新行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆