一段代码,可以给注释一下吗
某书上一段代码,可以给注释一下吗(//处请重点儿标注)?
编译有问题,可能是有错误。
#include <stream>
#include <string>
#include <vector>//
int main(int argc, char* argv[])
{
string filename;
cout<<"Please input the file name to open:";
cin>>filename;
if(filename.empty())
{
cerr<<"File name is empty(),bye..."<<endl;
return -2;
}
ifstream inFile(filename.c_str());
if(!inFile)
{
cerr<<"Unable open the file ...Bye"<<endl;
return -2;
}
string inBuf;
vector<string>text;//
while(inFile>>inBuf)//
{
for(int i=0;i<inBuf.size();i++)
if((char ch=inBuf[i])=='.')
{
ch='_';
inBuf[i]=ch;
}
}
text.push_back(inBuf);
if(text.empty())
return 0;
vector<string>::iterator iter=text.begin(),//
iend=text.end();//
while(iter!=iend)
{
cout<<*iter<<'\n';
++iter;
}
return 0;
}
问题点数:20、回复次数:3Top
1 楼rorot(rorot)回复于 2004-05-02 18:24:18 得分 17
#include <fstream>
#include <iostream>
#include <string>
// 标准库(STL)容器头文件
#include <vector>
using namespace std;
int main(int argc, char* argv[])
{
// 定义文件名
string filename;
cout << "Please input the file name to open: ";
cin >> filename;
// 文件名为空
if( filename.empty() )
{
// 向标准错误流输出错误信息(文件名空)
cerr << "File name is empty(),bye..." << endl;
return -2;
}
// 文件输入流 filename.c_str()输入char*型得文件名
ifstream inFile( filename.c_str() );
// inFile == NULL 则表示文件打开错误
if( !inFile )
{
// 向标准错误流输出错误信息(无法打开文件)
cerr << "Unable open the file ...Bye" << endl;
return -2;
}
// 定义输入缓冲区
string inBuf;
// 定义一个容器,这个容器里储存string类对象
vector<string> text;
// 如果从文件输入流里读入string型数据成功
// 则inFile >> inBuf 非0
while( inFile >> inBuf )
{
char ch;
// 把缓冲区里得所有得'.'变成'_'
for(int i=0; i<inBuf.size(); i++)
if((ch=inBuf[i]) == '.')
{
ch='_';
inBuf[i]=ch;
}
}
// 往容器压入缓冲区数据
text.push_back(inBuf);
// 如果容器空
if(text.empty())
return 0;
// 定义两个vector<string>型得迭代器,iter指向容器得开头
vector<string>::iterator iter=text.begin(),
// iend指向容器最后一个数据
// 得下一个内存单元
iend=text.end();
// 如果不相等,则表示容器里有数据
while(iter!=iend)
{
// *iter提领迭代器指向得数据,输出
cout << *iter << '\n';
// 指向下一个容器元素
++iter;
}
return 0;
}Top
2 楼rorot(rorot)回复于 2004-05-02 18:27:43 得分 2
不过我感觉你这个代码写得不伦不类得,按代码里得意思,应该是把一个文件里得所有得'.'转化成'_',但是偏偏他得while()循环却早早得结束了,而且某些地方得风格也待商酌,比如代码里对 iFile 得检测,和对文件名 filename 得处理就不怎么样.
Top
3 楼cyy219(学习中.....)回复于 2004-05-03 20:10:20 得分 1
顺便问个问题:
//**********************
//** ch19_1.cpp **
//**********************
#include<iostream.h>
void fn(int a, int b)
{
if(b==0)
cerr <<"zero encountered. "
<<"The message cannot be redirected";
else
cout <<a/b <<endl;
}
void main()
{
fn(20,2);
fn(20,0);
}
这个代码说执行结果为:
c>ch19_1>abc.dat
zero encountered.The message cannot be redirected.
写到cerr上的信息是不能被重定向,只能在屏幕上显示,但我运行后为
10
zero encountered.The message cannot be redirected.
怎么没见abc.dat文件呀?Top




