如何打印出文本文件的内容

How to print out contents of a text file

本文关键字:文件 文本 何打印 打印      更新时间:2023-10-16

我有一个文件,我想打印它的内容,但我无法让我的函数工作,有人可以帮忙吗?

这是我的代码:

int main()
{
  MenuText text;
  string test = "Champion";
  ofstream output("File.txt");
  text.save(output);
  fstream output ("File.txt");
  text.load("File.txt");//This is an error.
  text.print();

MenuText::MenuText()
{
    mText = "Default";
}
MenuText :: MenuText(string text)
{
mText = text;
}
void MenuText::print()
{
cout<< "Story= " << mText<< endl;
cout<< endl;
}
void MenuText::save(ofstream& outFile)
{
outFile<<   "/         .     ____    \   \    _ -. "
            //"/    /__        -    /_______\__\__ "
            "__  /   __        .      /_______//__//"
            "__//__/      _         -   ________  "
            "___    ___  ______    _____/     -  /    "
            "__    \   -.    \   ___ /_____/    ."
            "    __   \   -.      \   ___        "
            "-    ________\__  `___\_____           "
            ".     /_______//__/    /___//_____/ "<< mText<< endl;
cout<< endl;
outFile<< endl;
}
void MenuText::load(ifstream& inFile)
{
string garbage;
inFile>> garbage >> mText;
}
The errors are:
Error   1   error C2371: 'output' : redefinition; different basic types c:usersconordocumentscollegec++ programmingmaroonedmaroonedmainapp.cpp  15  1   Marooned
Error   2   error C2664: 'MenuText::load' : cannot convert parameter 1 from 'const char [9]' to 'std::ifstream &'   c:usersconordocumentscollegec++ programmingmaroonedmaroonedmainapp.cpp  16  1   Marooned

MenuText::load()ifstream&作为其唯一的参数,而不是const char*。创建一个ifstream实例并将其传递给MenuText::load()

std::ifstream input("File.txt");
if (input.is_open())
{
    text.load(input);
}

此外,close() output流以确保在创建ifstream之前刷新写入的所有数据。

MenuText::load()不会将文件的全部内容读入内存。它将存储文件中遇到的第二个字符串以mText因为operator>>将在第一个空格字符处停止读取。