C Fstream未显示写入的contenst

C++ fstream not displaying contenst written in

本文关键字:contenst 显示 Fstream      更新时间:2023-10-16

[编辑]将内容写入文件后,它不显示文本仅结束程序。我不是正确使用fstream吗?

fstream myfile;
int count = 0;
myfile.open("A3Problem2b.txt", ios::in | ios::out | ios::trunc);
if (!myfile.is_open())
{
    cout << "Cannot open file - A3Problem2b.txt"<< endl;
    exit(1);
}
char prompt[1000];
cout << "Enter a line of text with no punctuation <^Z to stop>:n";
cin.getline(prompt, 1000);
while ( !cin.eof() )
{
    myfile << prompt << endl;
    cin.getline(prompt, 1000);
}
myfile.getline(prompt, 1000);
while ( !myfile.eof() )
{
    cout << prompt << "n";
    myfile.getline(prompt, 1000);
}
myfile.close();

我认为您需要在从中阅读之前倒带流-fstream.seekg(0)

#include <iostream>
#include <fstream>

int main(int argc, char *argv[]) {
    std::fstream myfile;
    int count = 0;
    myfile.open("kb.nt", std::ios::in | std::ios::out | std::ios::trunc);
    if (!myfile.is_open())
    {
        std::cout << "Cannot open file - kb.nt"<< std::endl;
        exit(1);
    }
    char prompt[1000];
    std::cout << "Enter a line of text with no punctuation <^Z to stop>:n";
    while ( std::cin.getline(prompt, 1000) )
    {
        myfile << prompt << std::endl;
    }
    myfile.flush();
    myfile.seekg(0);
    while ( myfile.getline(prompt, 1000) )
    {
        std::cout << prompt << "n";
    }
    myfile.close();
}