第一题: 继续为 mystring类编写以下方法: 1:析构函数,释放buf指向的堆空间 2:编写 append(const mystring r) 为当前字符串尾部,拼接新的字符串r 3:编写 isEqual(const mystring r) 判断当前字符串和 字符串 r是否相等
#include <iostream>
#include <cstring>
using namespace std;
class mystring{
char* buf;
public:
mystring(const char* str);
mystring();
void show();
void setBuf(const mystring r){
free(this->buf);
int len = strlen(r.buf);
this->buf = (char*)calloc(1,len+1);
strcpy(this->buf, r.buf);
}
const char* getBuf()const{
return buf;
}
// ~mystring(){
// free(buf);
// }
void append(const mystring r){
int len = strlen(r.buf)+strlen(buf);
printf("%d\n", len);
char* temp = (char*)calloc(1, len+1);
memcpy(temp, buf, strlen(buf));
memcpy(temp+strlen(this->buf), r.buf, strlen(r.buf));
printf("%s\n", temp);
free(buf);
buf = temp;
}
int isEqual(const mystring r){
char* a = this->buf;
char* b = r.buf;
while(1){
if(*a>*b){
return 1;
}else if(*a<*b){
return -1;
}else if(*a==*b && *a==0 && *b==0){
return 0;
}else{
a++;
b++;
}
}
}
};
mystring::mystring(){
buf = (char*)calloc(1,1);
}
mystring::mystring(const char* str){
int len = strlen(str);
buf = (char*)calloc(1,len+1);
strcpy(buf,str);
}
void mystring::show(){
cout << buf << endl;
}
int main()
{
mystring ptr;
mystring str = "hello world", r = " bye 太奶";
ptr.setBuf(str);
cout << ptr.getBuf() << endl;
// ptr.setBuf("哇咔咔咔");
// cout << ptr.getBuf() << endl;
int n = ptr.isEqual(r);
printf("%d\n", n);
ptr.append(r);
cout << ptr.getBuf() << endl;
return 0;
}
第二题: 编写如下类: class File{ FILE* fp }; 1:构造函数,打开一个指定的文件 2:write函数 向文件中写入数据 3:read函数,从文件中读取数据,以string类型返回
#include <iostream>
#include <cstdio>
using namespace std;
class File{
FILE* fp;
public:
File();
File(char* add, char* opt ){
fp = fopen(add, opt);
}
~File(){
// fclose(rfp);
// fclose(wfp);
}
void write(char buf[64]){
fwrite(buf, 64, 1, fp);
}
string read(){
char buf[64] = {0};
fread(buf, sizeof(buf), 1, fp);
return buf;
}
};
int main()
{
char add[] = "C:/Users/zackz/Desktop/C++/test.txt", opt[] = "w", optr[] = "r";
File data(add, opt);
char txt[64] = {0};
cin >> txt;
data.write(txt);
File dat(add, optr);
cout << dat.read() << endl;
return 0;
}