将文件读取到没有字符串头文件的字符串对象中

问题描述

我想问一个有关读取C ++文件的问题。

我是C ++的初学者,正在学习文件I / O。

我有以下名为poem.txt的txt文件

Shall I compare thee to a summer's day?
Thou art more lovely and more temperate:
Rough winds do shake the darling buds of May,And summer's lease hath all too short a date:
Sometime too hot the eye of heaven shines,And often is his gold complexion dimm'd;
And every fair from fair sometime declines,By chance,or nature's changing course,untrimm'd;
But thy eternal summer shall not fade
nor lose possession of that fair thou ow'st;
nor shall Death brag thou wander'st in his shade,When in eternal lines to time thou grow'st;
So long as men can breathe or eyes can see,So long lives this,and this gives life to thee.

和相应的代码

#include <iostream>
#include <fstream>

int main () {
    std::ifstream in_file;
    in_file.open("poem.txt");
    if(!in_file) {
        std::cerr << "Problem opening file." << std::endl;
        return 1;
    }

    std::string line;

    while (std::getline(in_file,line)) {
        std::cout << line << std::endl;
    }

    in_file.close();
    return 0;
}

代码有效。由于我们在while循环中输出每一行,因此在终端中按上述方式输出了这首诗。

但是,我已经定义了一个字符串类型的变量std::string line,但是我没有包含#include <string>声明,但是此代码仍然有效。

搜索了cppreference,没有迹象表明<string><iostream>中也包含<fstream>

那么我如何在没有<string>标头声明的情况下将字符串对象打印到标准输出

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)