C++读取两行txt文字
时间: 2023-08-18 22:07:21 浏览: 56
你可以使用标准库中的`fstream`类来读取文件。以下是一个读取两行文本文件内容的示例代码:
```cpp
#include <iostream>
#include <fstream>
#include <string>
int main() {
std::ifstream file("example.txt"); // 打开文件
if (file.is_open()) {
std::string line1, line2;
std::getline(file, line1); // 读取第一行
std::getline(file, line2); // 读取第二行
std::cout << "第一行内容:" << line1 << std::endl;
std::cout << "第二行内容:" << line2 << std::endl;
file.close(); // 关闭文件
} else {
std::cout << "无法打开文件!" << std::endl;
}
return 0;
}
```
在上述代码中,我们首先创建了一个`ifstream`对象,并传入要打开的文件名(此处假设文件名为"example.txt")。然后,我们使用`getline`函数连续读取两行文本内容,并将其存储在两个字符串变量`line1`和`line2`中。最后,我们打印出这两行内容并关闭文件。
请确保将代码中的"example.txt"替换为你要读取的实际文件路径和文件名。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)