为什么这一行不输出我的文本文件?

Why does this line not output my text file?

本文关键字:我的 输出 文本 文件 一行 为什么      更新时间:2023-10-16

我目前正在读一本书,这本书正在教我关于C++,我遇到了一个问题。 我环顾了一下互联网,看看我是否能找到答案,但我似乎不太了解它们。 我写了这段代码...

#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main() {

// Writing the poem
string poem = "ntI never saw a man who looked";
poem.append("ntWith such a wistful eye");
poem.append("ntUpon that little tent of blue");
poem.append("ntWhich prisoners call the sky");

// More stuff
ofstream writer("poem.txt");

if(!writer) {
cout << "Error opening file for output" << endl;
return -1;  // Signal a termination
}
writer << poem << endl;
writer.close();

// Teminates the program
return 0;
}

我认为问题具体在于这条线writer << poem << endl;. 但我不确定我做错了什么。 我相当确定我做对了练习。

让我重申我的问题。 我有一个用一首诗生成的文本文件。 我正在尝试做的是将文件中的文本行输出到控制台(终端)。 我正在阅读的书要做writer << poem << endl;. 我这样做了,但没有输出,它只是生成带有文本的文件,仅此而已。

<小时 />

过了好一会儿。

事实证明,我只是很愚蠢,后来我意识到问题更多的是我没有充分阅读/理解文本。 我的印象是这段代码是为了输出文本。 我错了,但下面的答案真的帮助了我! 谢谢。

ofstream写入文件而不是屏幕,因此要将文件的内容发送到您的程序,请使用class ifstream

在程序中,如果您希望将文本写入文件,然后读回程序:

  • 在写入writer.close()后关闭文件后立即添加此代码:

    ifstream inFile("poem.txt");
    string sLine;
    while(getline(inFile, sLine))
    cout << sLine << endl;
    inFile.close();
    
  • 或者简单地使用类的对象fstream执行两次任务:写作/阅读。