首页 > 试题广场 >

编写程序实现如下功能:打开指定的一个文本文件,在每一行前加行

[问答题]

编写程序实现如下功能:打开指定的一个文本文件,在每一行前加行号。

推荐

解:

//b.cpp
#include <fstream.h>
#include <strstrea.h>
#include <stdlib.h>
void main(int argc, char* argv[])
{
strstream textfile;
{
ifstream in(argv[1]);
textfile << in.rdbuf();
}
ofstream out(argv[1]);
const int bsz = 100; 
char buf[bsz];
int line = 0; 
while(textfile.getline(buf, bsz)) { 
out.setf(ios::right, ios::adjustfield); 
out.width(1);
out << ++line << ". " << buf << endl;
}
}

编译后运行程序 b text1.txt

运行前 text1.txt 的内容为:

aaaaaaaaaaaa

bbbbbbbbbbbb

cccccccccccc

dddddddddddd

eeeeeeeeeeee

f f f f f f f f f f f f

gggggggggggg

hhhhhhhhhhhh

运行后 text1.txt 的内容为:

1. aaaaaaaaaaaa

2. bbbbbbbbbbbb

3. cccccccccccc

4. dddddddddddd

5. eeeeeeeeeeee

6. f f f f f f f f f f f f

7. gggggggggggg

8. hhhhhhhhhhhh


发表于 2018-04-18 20:31:28 回复(0)