Text Echo program

I have am program mostly written but I cant seem to get it to work so that the user can enter a filename and the program will echo the text from the specified file. Here is my code so far. someone please help me

#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>

using namespace std;

void eInput(ifstream &infile);

int main()
{
ifstream fin;
fin.open("input.txt");

if(fin.fail())
{
cout << "Opening input file failed." << endl
<< "Program Terminated" << endl;
exit(1);
}

echoInput(fin);

fin.close();

return 0;
}

void eInput(ifstream &infile)
{
char next;

infile.get(next);

while (!infile.eof())
{
cout << next;
infile.get(next);
}
}
echoInput(fin);

your function is called eInput(), not echoInput()
also note looping on eof() is not good:
http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong?noredirect=1&lq=1
this cplusplus page has an alternative way to achieve your ends:
http://www.cplusplus.com/reference/istream/istream/get/
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <fstream>
#include <string>

int main()
{
    std::string fname ;
    std::cout << "file name? " ;
    std::getline( std::cin, fname ) ;

    // http://en.cppreference.com/w/cpp/io/basic_ifstream/rdbuf
    // overload (9) http://en.cppreference.com/w/cpp/io/basic_ostream/operator_ltlt
    if( std::cout << std::ifstream(fname).rdbuf() ) ; // on success, do nothing more

    else // the attempt to dump the contents of the file to stdout failed
    {
        std::cerr << "could not open '" << fname << "' for input\n" ;
        return 1 ;
    }
}
Topic archived. No new replies allowed.