请使用VC6或使用【答题】菜单打开考生文件夹proj3下的工程proj3,其中定义了MyString类,一个用于表示字符串的类。成员函数reverse的功能是将字符串进行“反转”。例如,将字符串ABCDEF“反转”后,得到字符串FEDCBA;将字符串ABC

admin2016-08-19  35

问题 请使用VC6或使用【答题】菜单打开考生文件夹proj3下的工程proj3,其中定义了MyString类,一个用于表示字符串的类。成员函数reverse的功能是将字符串进行“反转”。例如,将字符串ABCDEF“反转”后,得到字符串FEDCBA;将字符串ABCDEFG“反转”后,得到字符串GFEDCBA。请编写成员函数reverse。在main函数中给出了一组测试数据,此时程序运行中应显示:
  读取输入文件…
  一反转前…
  STRl:ABCDEF
  sTR2=ABCDEFG
  …反转后…
  STRl=FEDCBA
  STR2=GFEDCBA
  要求:
  补充编制的内容写在“//**********333**********”与“//**********666**********”之间,不得修改程序的其他部分。
    注意:程序最后将结果输出到文件out.dat中,输出函数WriteToFile已经编译为obj文件,并且在本程序中调用。
1  //mgsering.h
2    #include  
3  #include
4  using namespace std;
5
6  class MyString{
7   public:
8   HyString(const char*s)
9   {
10    str  =new char[strlen(s) +1];
11    strcpy(sir,s);
12    }
13
14    ~NyString(){delete[]str;}
15
16    voLd reverse();
17    friend ostream&operator<(os-tream&os,const HyString&mystr)
18    {
19    os  <20    retuErn os;
21    }
22   private:
23    char*str;
24  };
25  void writeToFile(char *,  const HyString&);
1  //main.cpp
2  #include"mystring.h"
3  #inclucle
4
5    void MyString::reVerse()
6  {
7    //********333********
8
9
10    //********666********
11  }
12
13  int main()
14    {
15  char inname[128],pathname[80];
16    strcpy(pathname," ");
17    sprintf(inname,"in.dat",path-name);
18    cout<<"读取输入文件…\n\n";
19    ifstream infile(inname);
20    if(infile.fail())  {
21    cerr<<"打开输入文件失败!";
22    exit(1);
23    }
24
25    char buf[4096];
26    infile.getlihe(bur,4096);
27   HyString str1("ABCDEF"),sir2("AB-CDEFG"),str3(buf);
28    cout<<"---反转前---\n";
29  tout<<"STR1="<30    cout<<"STR2=" <31
32    str1.reverse();
33    str2.reverse();
34    str3.reverse();
35  tout<<"---反转后---\n";
36  tout<<"STR1="<37    cout<<"STR2  =" <38
39    writeToFile(pathname,$tr3);
40    return 0;
41  }

选项

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

最新回复(0)