5.3 C++

本文展示了如何在C++中处理C风格字符串的越界异常,以及使用类如MyStr和Figure/Alpha进行字符操作,同时包含异常捕获的main函数实例。
摘要由CSDN通过智能技术生成

1.C风格字符串的越界异常处理

#include <iostream>
#include <cstring>
using namespace std;
class MyStr{
    char str[200];
public:
    void set(string str);
    char at(unsigned int a);
};
void MyStr::set(string str){
    strcpy(this->str,str.c_str());
}
char MyStr::at(unsigned int a){
    if(strlen(str)<=a){
        throw int(2);
    }
        return str[a];
 
}
int main()
{
 
    MyStr s1;
    int n=0;
    s1.set("longthim");
    cin >> n;
    try {
        cout << s1.at(n) << endl;
    } catch (int) {
        cout << "越界访问" << endl;
        return -1;
    }
    return 0;
}

#include <iostream>
 
using namespace std;
class Figure{
    int n;
public:
    Figure():n(0){}
    void MyGetChar();
};
class Alpha{
    char ch;
public:
    Alpha():ch('a'){}
    void MyGetChar();
};
void Figure::MyGetChar(){
    if(n<=9){
        cout << n ;
        n++;
    }
}
void Alpha::MyGetChar(){
    if(ch<='z'){
        cout << ch;
        ch++;
    }
}
int main()
{
    Figure f1;
    Alpha a1;
    for(int i=0;i<26;i++){
        f1.MyGetChar();
        a1.MyGetChar();
    }
    return 0;
}
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值