简体   繁体   中英

How to print out contents of a text file

I have a file and i want to print ou the contents of it but i cant get my functions working can anyone help?

Here is my code:

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:\users\conor\documents\college\c++ programming\marooned\marooned\mainapp.cpp  15  1   Marooned
Error   2   error C2664: 'MenuText::load' : cannot convert parameter 1 from 'const char [9]' to 'std::ifstream &'   c:\users\conor\documents\college\c++ programming\marooned\marooned\mainapp.cpp  16  1   Marooned

MenuText::load() takes an ifstream& as its only argument, not a const char* . Create an instance of an ifstream and pass it to MenuText::load() :

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

Also, close() the output stream to ensure all data written is flushed before creating the ifstream .

The MenuText::load() will not read the entire content of the file into memory. It will store the second string encountered in the file to mText as operator>> will stop reading at the first whitespace character.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM