如何在C 中显示文件

How to display a file in c++?

本文关键字:显示文件      更新时间:2023-10-16

我需要有人编辑该代码,以便我可以显示一个文件!

#include <iostream>
#include <fstream>
using namespace std;
int main() 
{
     string data; //enter a data as a string 
     ifstream datafile; // input datafile as ifstream
     datafile.open("test.txt"); // open test file
}

不幸的是,您没有指定要读取和显示文件的方式。因此,我假设输出应该转到std::cout。在附件的提案中,有两种可能读取的可能性:逐行行,因为您将在任何文本编辑器中读取文件,或在新行中分别读取每个单词(以白色空格分隔的输入,即空白,制表符或线路断裂(。

#include <iostream>
#include <fstream>
#include <string>
int main()
{
    std::string data; //enter a data as a string
    std::ifstream datafile; // input datafile as ifstream
    datafile.open("Source.cpp"); // open test file
    // read line by line
    while (std::getline(datafile, data))
    {
        std::cout << data << std::endl;
    }
    /*
    // read each word (separated by white spaces)
    while (!datafile.eof())
    {
        datafile >> data;
        std::cout << data << std::endl;
    }
    */
    datafile.close();
    return 0;
}

没有错误处理。如果文件不存在或其他任何发生的情况都不会抓住任何例外。