为什么这一行不输出我的文本文件?
Why does this line not output my text file?
我目前正在读一本书,这本书正在教我关于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
执行两次任务:写作/阅读。
相关文章:
- 我的输出中有一个额外的 0,为什么会这样
- 为什么我的输出与输入不同?(C++)
- 当使用我在一个函数、另一个函数中修改的数组时,在我的输出中得到一个奇怪的负数
- "Program ended with exit code: 0"出现在我的输出的开头?
- 我的输出结果是 0 英寸C++.可能是什么问题
- 如何强制文件描述符缓冲我的输出
- 如果我决定输入 (1 2) 而它要求 x,为什么我的输出会出错,但如果我输入 (12) 工作正常
- 使用 ' ios::sync_with_stdio(0)' 测试运行时的差异时,为什么我的输出是碎片化的?
- 如何让我的输出显示输入金额的星号
- 为什么我的输出在到达代码的这一部分时冻结?
- 我的输出文件未显示解决方案
- 分析我的输出文件时,如何设置IDA加载源文件
- 为什么我的输出文件与输入文件不同
- 如何将我的输出用于另一个方程式
- 在我的桌子上仍将其添加到我的桌子的同时,我如何为我的输出添加一个额外的零
- 在我的输出之前,我该如何添加数字
- (c )我的输出.txt文件具有WIERD间距
- 如何准确格式化我的输出?
- 为什么我的输出是错误的
- 我对这个问题有问题,我的输出不正确