苦瓜黄瓜金银花 2021-07-30 13:09 采纳率: 80%
浏览 307
已结题

C++程序怎么在windows的cmd命令行中读取txt文件

类似于Python在cmd中读取txt文件 example.py < data.txt
两个问题
1、C++应该在cmd里面输入什么来读取txt文件
2、C++的cpp文件里,代码里面应该怎么写读取文件的代码

  • 写回答

1条回答 默认 最新

  • 广大菜鸟 2021-07-30 15:17
    关注

    img

    #include<iostream>
    #include<fstream>
    #include<string>
    using namespace std;
    void readFile(string filename);
    int main(int argc, char** argv) {// 第一个参数是本软件的exe
        /*for (int i = 0; i < argc; i++) // 查看有哪些命令
            cout << argv[i] << endl;*/
        if (argc == 3 && strcmp(argv[1],"-f")==0) {
            string filename = argv[2];// 读取文件显示
            readFile(filename);
        }
        else {
            cout << "请按照格式输入信息:文件.exe -f 文件名" << endl;
        }
    }
    void readFile(string filename) {
        ifstream inFile(filename, ios::in);
        string temp;
        if (!inFile) {
            cerr << "File could not be open." << endl;
        }
        while (getline(inFile, temp)) {
            cout << temp;
        }
        inFile.close();
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

问题事件

  • 系统已结题 8月7日
  • 已采纳回答 7月30日
  • 创建了问题 7月30日