c++ - 将文件读入没有字符串头文件的字符串对象
问题描述
我想问一个关于阅读 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>
标头声明的情况下将字符串对象打印到标准输出?
解决方案
推荐阅读
- java - azure API 应用程序每天第一次调用很慢
- javascript - node.js 和 gulp 中的 firebase 问题
- r - R dplyr - 循环数据帧列表 %>% 左连接 %>% 多个数据帧
- c# - 使用 dapper 从数据库返回一个 varchar
- java - 注销时删除所有 SharedPreferences
- python - Pandas 查询 group by /order by
- javascript - 具有可变内容的元素的动画高度
- php - 根据php中多维数组的值查找键
- angular - 事件发生后如何重绘html
- java - 如何在任何 Java 地图实现上测试空键?