Search code examples
c++fstreamreadfile

Inputting a file name and having the text read


I want the user to enter the name of a file, and if the file exists, print out all the contents of the file.

At the moment the uncommented code, takes a name of a file that the user inputs, for example. example.txt and prints out most (not the last word?) of the file. I've tried to implement this instead by using string (commented code is attempt) but clearly its incorrect.

I also wondering if i can automatically add .txt to the end of the user input, so that the console could ask - "which subject should we find more information on" user inputs "math" and it will open "math.txt"

Here is what I´ve tried:

#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
using namespace std;

int main() {


    char filename[50];
    //string getcontent;
    ifstream name;
    cin.getline(filename, 50);
    name.open(filename);

    if (!name.is_open()) {
        exit(EXIT_FAILURE);
    }

    char word[50];
    name >> word;
    while (name.good()) {
        cout << word << " ";
        name >> word;
    }

    //if (!name.is_open()) {
        //while (! filename).eof())
        //{
            //getline(name, getcontent)
            //cout << getcontent << endl;
        //}

        //exit(EXIT_FAILURE); //comes from cstdlib
    //}



    //}



    system("pause");
    return 0;
}

Solution

  • #include <iostream>
    #include <fstream>
    #include <cstdlib>
    #include <string>
    using namespace std;
    
    int main() {
    
        string filename;
        string getcontent;
        ifstream name;
        cin >> filename;
        filename.append(".txt"); // add extension.
        name.open(filename);
    
        if (!name.is_open()) {
            exit(EXIT_FAILURE);
        }
    
        while (true)
        {
            getline(name, getcontent);
            if (name.eof()) break;
            cout << getcontent << endl;
        }
    
        return 0;
    }