gpt4 book ai didi

c++ - 当一个 ofstream object.open() 被注释掉时会发生什么?

转载 作者:太空宇宙 更新时间:2023-11-03 10:41:48 25 4
gpt4 key购买 nike

#include<iostream>
#include<fstream>
#include<string>
#include<vector>

using namespace std;

int main(){

ofstream out;
ifstream in;

out.open("The Necessary Death of Charlie Countryman2.srt");
if (out.fail()) {
perror("The Necessary Death of Charlie Countryman2.srt");
}

in.open("The Necessary Death of Charlie Countryman.srt");
if (in.fail()) {
perror("The Necessary Death of Charlie Countryman.srt");
}

vector<string> input;
string inc;

while (getline(in, inc)) {
input.push_back(inc);
}

for (int k = 0; k < input.size(); k++) {
out << input[k] << endl;
}
return 0;
}

当我使用 ifstream 读取 somefile.txt 并使用 写入 anotherfile.txt 时>ofstream,一切正常,但假设我注释掉 out.open("anotherfile.txt") 并执行代码,没有错误当我打开 anotherfile.txt 时,它是空的。

我的问题是在

for (int k = 0; k < input.size(); k++) {
out << input[k] << endl;
}

会发生什么?

input[k] 发送到哪里或发送到什么?如果它是 cout,它会转到命令提示符,如果 out.open("anotherfile.txt") 没有被注释,那么它会转到 anotherfile.txt。

最佳答案

我假设 out 被声明为一个 ostream(或一个子类,例如 ofstream)。当您注释掉行 out.open(...) 时,out 被初始化为一个关闭的文件。因此,当您尝试写入它时,什么也没有发生,并且注入(inject)失败...但是未能测试它是否成功!

如果你测试它:

    for (int k = 0; k < input.size(); k++) {
out << input[k] << endl;
if out.fail() {
// process error condition...
}
}

您将传入错误条件分支,并且能够知道注入(inject)没有发生。

关于c++ - 当一个 ofstream object.open() 被注释掉时会发生什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34517318/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com