C++ Primer P8-4

本文探讨了使用C++实现字符串结构的方法,包括定义结构体、设置和显示字符串的功能。通过示例代码,展示了如何创建和操作字符串结构,以及如何进行字符串的赋值和显示,同时考虑了内存管理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <iostream>
#include <cstring>

using namespace std;
struct stringy{
    char * str;
    int ct;
};
stringy & set(stringy & a, char * b);
void show(char * a, int num = 1);
void show(stringy & a, int num = 1);
int main() {
    stringy beany;
    char testing[] = "reality isn't what it used to be.";
    set(beany, testing);
    show(beany);
    show(beany, 2);
    delete [] beany.str;
    testing[0] = 'D';
    testing[1] = 'u';
    show(testing);
    show(testing, 3);
    show("Done!");
    return 0;
}

stringy & set(stringy & a, char * b){
    char *p = new char;
    strcpy(p, b);
    a.str = p;
    a.ct = strlen(p);
    return a;
}

void show(char * a, int num){
    while (num > 0){
        cout << a << endl;
        num--;
    }
}

void show(stringy & a, int num){
    while(num > 0){
        cout << a.str << endl;
        cout << a.ct << endl;
        num--;
    }

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值