【问题标题】:I have been trying to read from a .txt using C++ but nothing gets outputted我一直在尝试使用 C++ 从 .txt 中读取,但没有输出任何内容
【发布时间】:2022-12-18 17:23:44
【问题描述】:

我需要帮助读取 C++ 上的 .txt 文件。我编写的代码应该接受命令行参数,其中之一是文件名,读取文件,将其内容存储在一个字符串中并打印该字符串的内容作为输出。我正在使用 ubuntu WSL 2 终端。每当我运行代码时,它都会使用参数接收命令并毫无问题地打开文件,但不会打印出任何内容。我不知道该怎么办。

#include <bits/stdc++.h>
#include <iostream>
#include <string>
#include <fstream>

using namespace std;

int main(int argc, char** argv){
    string filename = argv[1];

    cout << filename << endl; 

    string myText;
    ifstream myReadFile;
    
    myReadFile.open(filename);
    

    while(getline (myReadFile, myText)){
        cout << myText; 
    }

    cout << "Why is my code not doing what it is meant to " << endl;
    myReadFile.close();
    return 0;
}


That is what was in the file that was supposed to be printed out using cout. 

The man in the mirror does not exist. 

【问题讨论】:

    标签: c c++11 command-line-arguments ifstream wsl-2


    【解决方案1】:

    我在这里找到解决方案https://www.tutorialspoint.com/how-to-read-a-text-file-with-cplusplus,它可能对你有帮助

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-09-17
      • 2023-01-11
      • 1970-01-01
      • 1970-01-01
      • 2020-09-10
      • 1970-01-01
      • 1970-01-01
      • 2022-11-23
      相关资源
      最近更新 更多