C++ 中的 ostream 使用

发布于 2024-12-25 07:46:20 字数 196 浏览 4 评论 0原文

我有一个程序显示错误。如何解决错误并使用 ostream 显示输出 我在 ubuntu 中使用 g++ 编译器

#include<iostream>
using namespace std;
int main()
{
    ostream out;
    out<<"Hello World";
}

I have a program showing error. How to resolve the error and to use ostream to display output
I use g++ compiler in my ubuntu

#include<iostream>
using namespace std;
int main()
{
    ostream out;
    out<<"Hello World";
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

女中豪杰 2025-01-01 07:46:20

您想要的 ostream(附加到显示器)已被定义为 cout

#include<iostream>
using namespace std;
int main()
{
    cout<<"Hello World";
}

并非所有 ostream 都将流发送到终端显示器。

The ostream that you want (attached to the display) has already been defined as cout.

#include<iostream>
using namespace std;
int main()
{
    cout<<"Hello World";
}

Not all ostreams send the stream to the terminal display.

贩梦商人 2025-01-01 07:46:20

std::ostream 没有默认构造函数, this:

ostream out;

将出现编译时错误。

您可能想要使用 std::cout (如前所述)。

std::ostream does not have a default constructor, this:

ostream out;

will be a compile time error.

You are probably wanting to use std::cout (as has already been stated).

风情万种。 2025-01-01 07:46:20

首先,包含 #include 。其次,将 ofstream out 更改为 ofstream out("file.txt")

#include <iostream>
#include <fstream>
using namespace std;

int main () {

  ofstream out ("c:\\test5.txt");
  out<<"Hello World";
  out.close();

  return 0;
}

Firstly, include #include <fstream> . Secondly, change ofstream out to ofstream out("file.txt") .

#include <iostream>
#include <fstream>
using namespace std;

int main () {

  ofstream out ("c:\\test5.txt");
  out<<"Hello World";
  out.close();

  return 0;
}
淡莣 2025-01-01 07:46:20

为了进行一些输出,您需要获得正确的ostream。正如 Drew Dormann 向您展示的,您可以使用 std::cout 在标准输出上写入。您还可以使用 std::cerr 作为标准错误,最后,如果您想要在文件上写入,您还可以实例化自己的 fstream

#include <iostream>
#include <fstream>

int main()
{
    std::fstream outfile ("output.txt", fstream::out);

    outfile << "Hello World" << std::endl;

    // Always close streams
    outfile.close();
}

作为旁注:我建议不要在程序(请参阅此常见问题解答

In order to do some output you need to get the right ostream. As Drew Dormann showed you, you can use std::cout for writing on standard output. You can also use std::cerr for the standard error, and finally you can instantiate your own fstream if you want, for instance, to write on a file.

#include <iostream>
#include <fstream>

int main()
{
    std::fstream outfile ("output.txt", fstream::out);

    outfile << "Hello World" << std::endl;

    // Always close streams
    outfile.close();
}

As side note: i suggest not to export the std namespace (use namespace std) in your programs (see this faq)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文