求助

llcnllcn 2003-05-28 10:17:36
用C++写一个程序,完成下述任务:从文件中读取一个C++源程序,把其中的注释部分去掉,并将去掉注释部分后的源程序写到另一个文件中,而注释部分用cout输出到屏幕上。(提示:输出结果时,可以不考虑源程序的格式。问题:C++原程序中的注释部分有两种情况,及/*...*/和//)



大虾们请帮忙搞定程序,重分酬谢!
...全文
60 4 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
tuxw 2003-05-29
  • 打赏
  • 举报
回复
#include "stdafx.h"
#include <iostream>
#include <string>
#include <fstream>

using namespace std;

main()
{
ifstream fin( "d:\\temp\\c1.cpp" );
ofstream fout( "d:\\temp\\c2.cpp" );

string inBuf;
bool end = true; // 标记 /* */ 对是否结束

string::size_type first;

while( getline( fin, inBuf, '\n' ) ) // 每次处理一行
{
if(end) // 不在 /* */ 对中
{
first = inBuf.find_first_of( '/' );
if( first == string::npos && end )
{ // 连'/'都没有应该是语句了
fout << inBuf << endl;
continue;
}

while( first != string::npos )
{
if( inBuf[first+1] == '/' )
{ // 该行是双斜杠注释
fout << inBuf.substr( 0, first ) << endl; // 前半部分写入文件
cout << inBuf.substr( first ) << endl; // 后半部分输出
break;
}
else if( inBuf[first+1] == '*' )
{ // 开始 /* */ 对
fout << inBuf.substr( 0, first ) << endl;
cout << inBuf.substr( first ) << endl;
end = false;
}
first = inBuf.find( first, '/' );
}
}
else // 处理 /* 后面的部分,直到找到 */
{
first = inBuf.find( "*/" );
if( first != string::npos )
{ // 找到 */,
end = true;
cout << inBuf.substr(0, first+2) << endl;
// 这里没有考虑 */ 后还有语句或注释的情况
continue;
}
else
cout << inBuf << endl;
}
}
fin.close();
fout.close();
return 0;
}
煜知搬砖者 2003-05-29
  • 打赏
  • 举报
回复
hehe,学习。up
bm1408 2003-05-29
  • 打赏
  • 举报
回复
强人!
up!
adams_here 2003-05-28
  • 打赏
  • 举报
回复
可以这样:
一行行读入到一个CString类的变量中,寻找/*...*/和//,如果有//那么剩下的就全是注释,不要了;如果是/*,再找有没有*/,没有的话读下一行,再找,一直到找到为止,把这其中的内容都去掉。
呵呵,说的有些笼统。

70,020

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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