用c++编写程序实现如下功能:打开指定的一个文本文件(11-9.txt),在每一行前加行号后将其输出到另一个文本文件中。格式控制为右对齐
时间: 2024-05-16 07:16:29 浏览: 8
以下是使用C++实现该功能的代码:
```c++
#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;
int main() {
ifstream inFile("11-9.txt");
ofstream outFile("output.txt");
if (!inFile) {
cerr << "Failed to open input file." << endl;
return 1;
}
if (!outFile) {
cerr << "Failed to open output file." << endl;
return 1;
}
string line;
int lineNumber = 1;
while (getline(inFile, line)) {
outFile << right << setw(4) << lineNumber << " " << line << endl;
lineNumber++;
}
inFile.close();
outFile.close();
return 0;
}
```
解释:
1. 首先,我们使用 `ifstream` 和 `ofstream` 分别打开输入和输出文件。如果打开文件失败,我们将输出错误信息并返回 1。
2. 然后,我们使用 `getline` 函数逐行读取输入文件,同时记录行号。对于每一行,我们使用 `setw` 函数设置输出宽度为 4,使用 `right` 函数使其右对齐,并输出行号和行内容到输出文件中。
3. 最后,我们关闭输入和输出文件,并返回 0 表示程序正常结束。