c++ primer 10.3.9例题(自己实现版)

题目:给出一个string对象,把它转换成另一个string对象。本程序的输入是两个文件,第一个文件包含了若干对单词,没对的第一个单词将出现在输入字符串中,而第二个单词则用于输出。本质上,这个文件提供的是单词转换的集合——在遇到第一个单词时,应该将之替代为第二个单词。第二个文件则提供了需要转换的文本,如果单词转换的文件内容是:

{"'em", "them" }, {"cuz", "because" }, {"gratz", "grateful"}, {"i", "I" }, {"nah", "no" },
{"pos", "supposed" }, {"sez", "said" }, {"tanx", "thanks" }, {"wuz", "was" } 

而要转换的文本是:

{"nah", "i", "sez", "tanx", "i", "wuz", "pos", "to", 
"not", "cuz", "i", "wuz", "gratz" }

则程序将产生如下输出:

no I said thanks I was supposed to not because I was grateful



#include <iostream>

#include <fstream>
#include <map>
#include <string>


struct map_wk
{
char cha[10];
char chb[10];
};


using namespace std;
int main()
{
map< string, string > mapa;
map_wk mapw; //定义结构体

map_wk map_file1[ 10 ] = { {"'em", "them" }, {"cuz", "because" }, {"gratz", "grateful"}, {"i", "I" }, {"nah", "no" },
{"pos", "supposed" }, {"sez", "said" }, {"tanx", "thanks" }, {"wuz", "was" } };


char chp[15][10] = {"nah", "i", "sez", "tanx", "i", "wuz", "pos", "to", 
"not", "cuz", "i", "wuz", "gratz", '\0' };

fstream finout_file1, finout_file2;
finout_file1.open("file1.txt", ios::in | ios::out | ios::trunc | ios::binary ); //change++ ios::trunc
finout_file2.open("file2.txt", ios::in | ios::out | ios::trunc | ios::binary ); //change++ ios::trunc
//这里加下is_open()的判断
if( !finout_file1.is_open() )
{
cerr<<"Can't open file1 file for output:\n";
exit( EXIT_FAILURE );
}
if( !finout_file2.is_open() )
{
cerr<<"Can't open file2 file for output:\n";
exit( EXIT_FAILURE );
}
/*------------------------------------*/


map_wk mapw_file1[10]; //change  ++
for( int i = 0; i < 10; i++ )
{
if( map_file1[i].cha[0] == '\0' )
break;
finout_file1.write( ( char * ) &map_file1[i], sizeof map_file1[i] );
}



/*for( int i = 0; i < 15; i++ )
cout<<"chp[ " <<i <<" ] = " <<chp[i] <<endl; //debug
*/
for( int i = 0; chp[i][ 0 ] != '\0'; i++ )
{
finout_file2.write( ( char * ) & ( chp[i] ), sizeof( chp[i] ) ); //写第二个文件
}
finout_file1.clear();
finout_file2.clear();
finout_file1.seekg( 0 );
finout_file2.seekg( 0 );
finout_file1.seekp( 0 );
finout_file2.seekp( 0 );
//map_wk mapw;
string strpa, strpb;


while( finout_file1.read( ( char * ) & mapw, sizeof mapw ) )
{
strpa = mapw.cha ;
strpb = mapw.chb;
mapa.insert( make_pair( strpa, strpb ) );
}
finout_file1.close();

char chw[10];
string stra;
map< string, string >::iterator iter;
while( finout_file2.read( ( char * ) & chw, sizeof chw ) )
{
//cout<<"chw: " <<chw <<endl;
stra = chw; //
iter = mapa.find( stra );
if( iter == mapa.end() )
cout<<chw <<" ";
else
cout<<iter->second <<" ";
}
finout_file2.close();




return 0;
} //程序暂时到这里结束




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值