用C++给一个文本文件每一行加上行号存储到另一个文本文件中并读该文件
时间: 2024-03-09 21:48:37 浏览: 121
好的,我可以帮你解答这个问题。你可以使用C++的文件流来实现这个功能。具体步骤如下:
1. 打开要读取的文件和要写入的文件。可以使用ifstream和ofstream两个类来分别打开两个文件。
```c++
ifstream infile("input.txt");
ofstream outfile("output.txt");
```
2. 定义一个计数器变量,用来记录当前处理到的行号。
```c++
int count = 1;
```
3. 使用while循环逐行读取输入文件的内容,并在每一行前加上行号,然后写入输出文件中。
```c++
string line;
while (getline(infile, line)) {
outfile << count << ": " << line << endl;
count++;
}
```
4. 关闭文件流。
```c++
infile.close();
outfile.close();
```
完整代码如下:
```c++
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
ifstream infile("input.txt");
ofstream outfile("output.txt");
int count = 1;
string line;
while (getline(infile, line)) {
outfile << count << ": " << line << endl;
count++;
}
infile.close();
outfile.close();
ifstream newfile("output.txt");
while (getline(newfile, line)) {
cout << line << endl;
}
newfile.close();
return 0;
}
```
注意,这里使用了getline函数来逐行读取文件内容。最后,我们再次使用文件流来读取输出文件的内容,并在控制台上输出。
阅读全文
相关推荐
















