请打开考生文件夹下的解决方案文件proj3,其中定义了MyString类,一个用于表示字符串的类。成员函数reverse的功能是将字符串进行“反转”。例如,将字符串ABCDEF“反转”后,得到字符串FEDCBA;将字符串ABCDEFG“反转”后,得到字符串

admin2020-07-23  27

问题 请打开考生文件夹下的解决方案文件proj3,其中定义了MyString类,一个用于表示字符串的类。成员函数reverse的功能是将字符串进行“反转”。例如,将字符串ABCDEF“反转”后,得到字符串FEDCBA;将字符串ABCDEFG“反转”后,得到字符串GFEDCBA。请编写成员函数reverse。在main函数中给出了一组测试数据,此时程序运行中应显示:
读取输入文件...
---反转前---
STR1=ABCDEF
STR2=ABCDEFG
---反转后---
STR1=FEDCBA
STR2=GFEDCBA
要求:
补充编制的内容写在“//********333********”与“//********666********”之间,不得修改程序的其他部分。
注意:程序最后将结果输出到文件out.dat中,输出函数WriteToFile已经编译为obj文件,并且在本程序中调用。
//mgsering.h
#include<iostream>
#include<cstring>
using namespace std;
class MyString{
public:
MyString(const char*s)
{
str=new char[strlen(s)+1];
strcpy(str,s);
}
~MyString( ){delete[ ]str;)
void reverse( );
friend ostream&operator<<(ostream&os,const MyString&mystr)
{
os<<mystr.str;
return os;
}
private:
char*str;
};
void writeToFile(char*,constMyString&);
//main.cpp
#include"mystring.h"
#include<fstream>
void MyString::reverse( )
{
//********333********


//********666********
}
int main( )
{
char inname[128],pathname[80];
strcpy(pathname," ");
sprintf(inname,"in.dat",pathname);
cout<<"读取输入文件...\n\n";
ifstream infile(inname);
if(infile.fail( )){
cerr<<"打开输入文件失败!";
exit(1);
}
char buf[4096];
infile.getline(buf,4096);
MyStringstrl(”ABCDEF”),
Str2("ABCDEFG"),Sstr3(buf);
cout<<"---反转前---\n";
cout<<"STR1="<<str1<<endl;
cout<<"STR2="<<str2<<endl<<endl;
Strl.reverse( );
Str2.reverse( );
Str3.reverse( );
cout<<"---反转后---\n";
cout<<"STR1=”<<str1<<endl;
cout<<"STR2="<<Str2<<endl<<endl;
writeToFile(pathname,str3);
returnR0;
}

选项

答案int length:strlen(str);//把字符串str的长度赋值给lenth for(int i=0,j=length-1;i<j;i++,j--) //从i=0,j=length-1,i<j为条件开始遍历,并把Str[i]和Str[j]交换 { char temp=str[i];//给定义的临时变量temp赋值为str[i] str[i]=str[j];//给str[i]赋值str[j] str[j]=temp;//给str[j]赋值为temp

解析 主要考查考生对动态数组的掌握,先看题目要求:成员函数reverse的功能是将字符串进行“反转”。再由类的定义可知,字符串存放在动态数组str中,由strlen函数得出字符串的长度,最后一个字符的下标为length-1,第一个字符的下标为0,将这两个字符交换,然后j依次减1同时i依次加1,继续交换,直到i大于j时停止循环即可。
转载请注明原文地址:https://kaotiyun.com/show/l9yp777K
0

随机试题
最新回复(0)