【问题标题】:How do I print out the contents of a file? C++ File Stream如何打印文件的内容? C++ 文件流
【发布时间】:2016-05-14 02:49:55
【问题描述】:

我正在使用 fstream 和 C++,我想要我的程序做的就是将我的 .txt 文件的内容打印到终端。这可能很简单,但是我在网上查看了很多东西,但找不到任何可以帮助我的东西。我怎样才能做到这一点?这是我到目前为止的代码:

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

int main() {
    string output;
    ifstream myfile;
    ofstream myfile2;

    string STRING;
    myfile.open ("/Volumes/LFARLEIGH/Lucas.txt");

    myfile2 << "Lucas, It Worked";

        myfile >> STRING;
        cout << STRING << endl;
    myfile.close();


    return 0;
}

提前谢谢你。如果这很简单,请原谅我,因为我对 C++ 很陌生

【问题讨论】:

  • 您是否遇到错误
  • cout 后面多了一个 '}'
  • 你打开同一个文件两次?
  • 对这些事情感到抱歉 - 不相关。我没有收到错误,文件中的文本没有出现
  • 见过this question?

标签: c++ iostream fstream


【解决方案1】:

当此功能已在标准 C++ 库中实现时,没有理由在这里重新发明轮子。

#include <iostream>
#include <fstream>

int main()
{
    std::ifstream f("file.txt");

    if (f.is_open())
        std::cout << f.rdbuf();
}

【讨论】:

    【解决方案2】:
    #include <iostream>
    #include <fstream>
    
    int main()
    {
        string name ;
        std::ifstream dataFile("file.txt");
        while (!dataFile.fail() && !dataFile.eof() )
        {
              dataFile >> name ;
              cout << name << endl;
        }
    

    【讨论】:

    • 您能解释一下您的代码吗?为什么比accepted answer更好?
    • 在回答时,请提及实际发布的代码中的错误之处以及更正的内容以及为什么必须以这种方式更正。下面的链接会帮助你。 stackoverflow.com/help/how-to-answer
    【解决方案3】:

    试试这个,只是在某些地方进行了修改。您曾尝试使用提取器(即 ifstream)打开文件,但使用插入器(即 ofstream)覆盖该文件 在不打开文件的情况下,ifstreamofstream 是两个不同的类。所以,他们不明白。

    #include<iostream>
    #include<fstream>
    
    using namespace std;
    
    int main(){
    
        string output;
        ifstream myfile;
        ofstream myfile2;
    
        string STRING;
        // output stream || inserting
        myfile2.open ("/Volumes/LFARLEIGH/Lucas.txt");
    
        myfile2 << "Lucas, It Worked";
    
    
        myfile2.close();
    
        // input stream || extracting
    
        myfile.open("/Volumes/LFARLEIGH/Lucas.txt");
    
            myfile >> STRING;
            cout << STRING << endl;
        myfile.close();
    
    
       return 0;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-02
      • 2012-06-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-01
      • 2016-01-10
      • 1970-01-01
      相关资源
      最近更新 更多