C++类练习(一)

C++类练习(一),第1张

  1. 有这么个需求,所有的在校生都必须有学号,所以能不能实现实例化一个Student对象之后,就要求输入学号,不存在一个没有学号的Student对象被实例化出来,大家明白了吗?也就是类似于 stud1 这样的对象是不允许存在的,因为其没有学号。


#include
#include
using namespace std;

class Cstudent
{
    public:
    	char name[50];
    	char sex;
    	int num;
    	int age;
    public:
    	Cstudent()									//定义构造函数,没有输入学号要求重新输入
        {
            cout << "缺少学号" << endl;
        }
    	Cstudent(num1)								//定义带参的构造函数,满足条件
        {
            memset(name,0,50);
            sex = f;
            num = num1;
            age = 20;
            cout << "Cstudent::Cstudent" << endl;
        }
}
int main()
{
    Cstudent();
    Cstudent(18);
    return 0;
}
    
  1. 实现一个函数,该函数的声明如下:
    bool string_upper_diy(char str[], int str_len, bool b_odd_pos = true);
    功能为对字符串指定位置的字符变换为大写。



    str 参数为字符串的指针;
    str_len 为字符串的长度;
    b_odd_pos 为true的时候,就要将 str 字符串中的奇数位置的字符变为大写,同时将非奇数位置的字符变为小写;
    b_odd_pos 为false的时候,就要将 str 字符串中的奇数位置的字符变为小写,同时将非奇数位置的字符变为大写;
    奇数指的是:1,3,5,7,9,11,13,15,17,19…以此类推;
    大家明白了吗?动手试着做一做!

#include
#include
using namespace std;

bool string_upper_diy(char str[],int str_len,bool b_odd_pos = true)
{
    int i;
    if(b_odd_pos)
    {
        if(i % 2 != 0)
        {
            if(str[i-1]>='a'&&str[i-1]<='z')
            {
                str[i-1] = str[i-1]-'a'+'A';
            }
        }
        else
        {
            if(str[i-1]>='A'&&str[i-1]<='Z')
            {
                str[i-1] = str[i-1]-'A'+'a';
            }
        }
    }
    else
    {
        if(i % 2 != 0)
        {
            if(str[i-1]>='A'&&str[i-1]<='Z')
            {
                str[i-1] = str[i-1]-'A'+'a';
            }
        }
		else
        {
			if(str[i-1]>='a'&&str[i-1]<='z')
            {
                str[i-1] = str[i-1]-'a'+'A';
            }
        }
    }
    return false;
}
int main()
{
    char a[20];
    cout << "请输入字符串,不超过9个字符,以0结尾。


" << endl; cin.get(a,10,'0'); cout << "变化前:" << endl; string_upper_diy(a,sizeof(a),true); cout << "变化后:" << endl; return 0; }

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/584453.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-04-12
下一篇2022-04-12

发表评论

登录后才能评论

评论列表(0条)

    保存