C++期末考试,请帮忙啊!

qingzhai 2009-01-12 12:22:10
write a program to copy one text file into another text file into another text file in which the lines are numbered 1,2,3...with a number at the left of each line.
写一个程序将一个文件的内容复制到另一个文件上,并在内容前面的每一行标记上1,2,3...
...全文
135 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
xiaoyisnail 2009-01-12
  • 打赏
  • 举报
回复

#include <fstream>
#include <iostream>
#include <string>
using namespace std;

int main()
{
ifstream in("in.txt",fstream::in);
if(!in)
{
cerr<<"error"<<endl;
exit(1);
}

ofstream out("out.txt",fstream::out);
if(!out)
{
cerr<<"error"<<endl;
exit(1);
}

string line;
int line_no = 1;
while(getline(in, line))
{
out<<line_no<<" "<<line<<endl;
++line_no;
}

return 0;
}
tangshuiling 2009-01-12
  • 打赏
  • 举报
回复

类似的代码可实现:

int i=1;
string str;
ifstream ifile("c:\\ifile.txt"); //没有必要的异常检测,楼主自己写吧
ofstream ofile("c:\\ofile.txt");
while(getline(ifile,str))
{
ofile<<i++;
str=':'+str;
ofile<<str<<endl;
}

fo1_sky 2009-01-12
  • 打赏
  • 举报
回复
基本文件读写呀
Jinhao 2009-01-12
  • 打赏
  • 举报
回复

#include <iostream>
#include <sstream>

int main( int argc, char* argv )
{
std::string str = "646f20697420796f757273656c66";
char * dest = new char[str.size()];
for(int i = 0; i < str.size() / 2; ++i)
{
std::stringstream ss;
ss<<std::hex<<str.substr(i * 2, 2);
int x;
ss>>x;
dest[i] = x;
}
dest[str.size()/2] = 0;
std::cout<<dest<<std::endl;
delete [] dest;
std::system("pause");
}

无话可言 2009-01-12
  • 打赏
  • 举报
回复
ifstream infile("1.txt");
if(!infile){
cout<<"Can't open 1.txt"<<endl;
return 1;
}
ofstream outfile("2.txt", ios::app);
if(!outfile){
cout<<"Can't open 2.txt"<<endl;
return 1;
}
int lineNo = 1;
string lineString;
outfile <<endl; //And a new line.
//Read One line and put in line, write the formate to outfile
while(infile >> lineString){
outfile << lineNo << " " << lineString <<endl;
lineNo++;
}

infile.close();
outfile.close();
OenAuth.Net 2009-01-12
  • 打赏
  • 举报
回复
百度一下,文件按行读写
qingzhai 2009-01-12
  • 打赏
  • 举报
回复
frcsun 2009-01-12
  • 打赏
  • 举报
回复
今晚我们也考试,先看下,晚上考完了在解决~~~
waizqfor 2009-01-12
  • 打赏
  • 举报
回复
[Quote=引用 8 楼 xiaoyisnail 的回复:]
C/C++ code
#include <fstream>
#include <iostream>
#include <string>
using namespace std;

int main()
{
ifstream in("in.txt",fstream::in);
if(!in)
{
cerr<<"error"<<endl;
exit(1);
}

ofstream out("out.txt",fstream::out);
if(!out)
{
cerr<<"error"<<endl;
exit(1);
}

string line;
int line_no = 1;
while…
[/Quote]
文件按行读写 换行在前面加一个标记(1 2 3) 基本文件操作

65,210

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧