编写程序实现如下功能:打开指定的一个文本文件,在每一行前加行号。
解:
//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
7. gggggggggggg
8. hhhhhhhhhhhh
这道题你会答吗?花几分钟告诉大家答案吧!
扫描二维码,关注牛客网
下载牛客APP,随时随地刷题
解:
编译后运行程序 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
7. gggggggggggg
8. hhhhhhhhhhhh