Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ How do I print a .txt file verbatim?

I have a file that I am trying to print to the screen, but all it returns is "0x28fe88", when the file itself is 13 columns by a couple hundred rows.

#include <iostream>
#include <fstream>
#include <istream>
#include <ostream>
#include <cstdlib>
using namespace std;

int main()
{
    //Opens .txt file
    ifstream infile1;
    infile1.open("Taylor.txt");

    //Fail check
    if(infile1.fail())
    {
        cout << "File failed to open.\n";
        exit(1);
    }

    //Prints file to screen (not correctly)
    cout << infile1;

    //Closes file
    infile1.close();
    return 0;
}

I would otherwise not post the full code, but I hope it is short enough to not warrant catching flak.

like image 977
Tilt-Shifted Avatar asked Aug 13 '13 20:08

Tilt-Shifted


1 Answers

To just print out text file use this cout << infile1.rdbuf();, because now you're printing a pointer to a file.

EDIT: If this didn't work for you, the closest thing to it would be to read file character by character. There are other ways around it using strings, but this code will do just fine:

while(infile1.good()) 
    cout << (char)infile1.get();

It reads character code while the file is good to read and instantly converts it to char (might need some modifications for UNICODE) and prints it out.

like image 72
FrogTheFrog Avatar answered Nov 10 '22 06:11

FrogTheFrog