输入文件名并读取文本

Inputting a file name and having the text read

我想让用户输入一个文件名,如果这个文件存在,打印出这个文件的所有内容。

目前未注释的代码,例如,采用用户输入的文件名。 example.txt 并打印出文件的大部分(不是最后一个词?)。我试图通过使用字符串来实现这一点(尝试注释代码)但显然它是不正确的。

我还想知道我是否可以自动将 .txt 添加到用户输入的末尾,以便控制台可以询问 - "which subject should we find more information on" 用户输入 "math" 并且它将打开 "math.txt"

这是我试过的方法:

#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;
}
#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;
}

我找到了这个,它帮助我解决了一个稍微不同的问题,我也认为我可能能够提供帮助。这在 windows 中编码。 (我是初学者,如果我犯了一些明显的错误,请原谅我)

#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;
ifstream fin;
int main()
{
    //char filename[50],word[50];
    string filename,word;
    //cin.getline(filename,50);
    getline(cin,filename);
    //strcat(filename,".txt");
    filename.append(".txt");
    fin.open(filename);
    if(fin.is_open())
        while(fin>>word)
            cout<<word<<endl;
    else
        cout<<"No such file"<<endl;
    return 0;
}