c++如何读取并输出TXT文件的内容
时间: 2023-12-27 18:05:22 浏览: 146
可以使用C++中的fstream库来读取和输出TXT文件的内容。以下是一个简单的示例代码:
```c++
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
ifstream file("example.txt");
string line;
if (file.is_open()) {
while (getline(file, line)) {
cout << line << endl;
}
file.close();
}
else {
cout << "Unable to open file" << endl;
}
return 0;
}
```
上述代码中,我们打开了名为 "example.txt" 的文件,并使用while循环逐行读取文件内容,并将每行输出到控制台。如果文件无法打开,则输出一条错误消息。
相关问题
用c++读取并输出TXT文件中的某几行
你好,我可以回答这个问题。要读取并输出TXT文件中的某几行,可以使用C语言中的文件操作函数。首先需要打开文件,然后使用循环读取文件中的每一行,判断是否为需要输出的行,如果是则输出。具体代码可以参考以下示例:
```
#include <stdio.h>
int main()
{
FILE *fp;
char buffer[1024];
int line_num = ;
int start_line = 2;
int end_line = 4;
fp = fopen("file.txt", "r");
if (fp == NULL)
{
printf("Failed to open file\n");
return 1;
}
while (fgets(buffer, sizeof(buffer), fp) != NULL)
{
line_num++;
if (line_num >= start_line && line_num <= end_line)
{
printf("%s", buffer);
}
}
fclose(fp);
return ;
}
```
其中,start_line 和 end_line 分别表示需要输出的起始行和结束行,可以根据实际需求进行修改。
C++读取文件内容·并输出
可以通过以下代码在C++中读取文件内容并输出:
```cpp
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
ifstream infile("filename.txt"); // 打开文件
string line;
while (getline(infile, line)) { // 逐行读取文件内容
cout << line << endl; // 输出每一行内容
}
infile.close(); // 关闭文件
return 0;
}
```
其中,`filename.txt` 表示要读取的文件名。通过 `ifstream` 类型的对象 `infile` 打开文件,并使用 `getline` 函数逐行读取文件内容,将读取的每一行内容存储在 `string` 类型的变量 `line` 中,并使用 `cout` 输出每一行内容。最后使用 `close` 函数关闭文件。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![](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)