首页 > 解决方案 > 将文件读入没有字符串头文件的字符串对象

问题描述

我想问一个关于阅读 C++ 文件的问题。

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

我有以下名为的txt文件poem.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>or中<fstream>

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

标签: c++file-iofstream

解决方案


推荐阅读