gpt4 book ai didi

c++ - 打印到文件和控制台 C++

转载 作者:行者123 更新时间:2023-11-28 04:38:03 25 4
gpt4 key购买 nike

我正在尝试记录我的事件,所以我想到使用 ostringstream 来保存输出,然后将它发送到一个函数,在该函数中我将输出打印在屏幕上和文件 fstream fileOut 上。它不会工作,它只是给我随机数,似乎不会在同一个文件上输出所有新输出,而是每次都创建一个新文件并删除之前的内容。我该怎么做?

打印发生的地方:

void Event::output(ostringstream* info) {
std::cout << info << std::endl;
fileOut << info << std::endl;
}

输出发生的地方:

ostringstream o;
if (time < SIM_TIME) {

if (status->tryAssemble(train)) {
Time ct;
ct.fromMinutes(time);
o << ct << " Train [" << train->getTrainNumber() << "] ";

Time t(0, DELAY_TIME);
o << "(ASSEMBLED) from " << train->getStart() << " " << train->getScheduledStartTime() <<
" (" << train->getStartTime() << ") to " << train->getDest() << " " << train->getScheduledDestTime() <<
" (" << train->getDestTime() << ") delay (" << train->getDelay() << ") speed=" << train->getScheduledSpeed() <<
" km/h is now assembled, arriving at the plateform at " << train->getStartTime() - t << endl << endl;

fileOut.open("testfile.txt", std::ios::out);
if (!fileOut.is_open())
exit(1); //could not open file
output(&o);
train->setStatus(ASSEMBLED);
time += ASSEMBLE_TIME;
Event *event = new ReadyEvent(simulation, status, time, train);
simulation->addEvent(event);

最佳答案

It wont work, it just gives me random numbers

您正在传递 ostringstream通过指针指向您的函数。没有 operator<<这需要 ostringstream*指针作为输入并打印其字符串内容。但是有一个 operator<<这需要 void*作为输入并打印指针指向的内存地址。那就是您看到的“随机数”。任何类型的指针都可以分配给 void*指针。

您需要取消引用 ostringstream*访问实际 ostringstream 的指针目的。即便如此,还是没有operator<<这需要 ostringstream作为输入。然而,ostringstream有一个 str()返回 std::string 的方法, 并且有一个 operator<<用于打印 std::string :

void Event::output(ostringstream* info) {
std::string s = info->str();
std::cout << s << std::endl;
fileOut << s << std::endl;
}

话虽这么说,你应该通过 ostringstream通过 const 引用而不是通过指针,因为该函数不允许 null ostringstream被传入,它不会修改 ostringstream以任何方式:

void Event::output(const ostringstream &info) {
std::string s = info.str();
std::cout << s << std::endl;
fileOut << s << std::endl;
}

...

output(o);

seem not to output all new outputs on the same file but just creates a new file everytime and deletes what was on it before.

那是因为您没有使用 app 打开文件或 ate标记 1,因此它每次都会创建一个新文件,并丢弃任何现有文件的内容。如果您想附加到现有文件,则需要:

  • 使用 ate标记为“打开后立即搜索到流的末尾”:

    fileOut.open("testfile.txt", std::ios::out | std::ios::ate);
  • 使用 app标记为“在每次写入之前寻找流的末尾”:

    fileOut.open("testfile.txt", std::ios::out | std::ios::app);

1:如果fileOutstd::ofstream , 你不需要指定 std::ios::out明确地。

关于c++ - 打印到文件和控制台 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50867751/

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