C++结构体:定义sex成员变量的数据类型为char还是string

1、sex定义char类型易出现的错误:

// 错误程序:
#include <bits/stdc++.h> 
using namespace std;
struct student{
	string name;
	char[2] sex;   // 有问题
	int age;
	double weight;
};
int main(){
	student stu;
	stu.name="zhangsan";
	stu.sex='ml';   // 有问题
	stu.age=12;
	stu.weight=90.54;
	cout << stu.name << stu.sex << stu.age << stu.weight;
	
	return 0;
}

错误分析:

  1. char[2] sex; 声明了一个长度为 2 的字符数组,这个数组只能存储 2 个字符(包括结尾的空字符 \0)。但是你试图将字符串 "ml" 赋给它,这不符合要求,因为 "ml" 实际上是一个长度为 3 的字符串(包括结尾的 \0)。

  2. stu.sex = 'ml'; 这一行也不对,因为 'ml' 是一个错误的字符常量,它应该是 char 类型,不能表示一个字符串。

2、修正后的代码:

方法 1: 使用字符数组存储性别的前两个字符
#include <bits/stdc++.h>
using namespace std;

struct student {
    string name;
    char sex[2]; // 使用字符数组存储 2 个字符
    int age;
    double weight;
};

int main() {
    student stu;
    stu.name = "zhangsan";
    stu.sex[0] = 'm';  // 设置 sex 数组的第一个字符
    stu.sex[1] = 'l';  // 设置 sex 数组的第二个字符
    stu.age = 12;
    stu.weight = 90.54;

    // 输出信息   注意点stu.sex[0],stu.sex[1]
    cout << stu.name << " " << stu.sex[0] << stu.sex[1] << " " << stu.age << " " << stu.weight << endl;

    return 0;
}
方法 2: 使用 string 类型存储性别
#include <bits/stdc++.h>
using namespace std;

struct student {
    string name;
    string sex; // 使用 string 类型存储性别
    int age;
    double weight;
};

int main() {
    student stu;
    stu.name = "zhangsan";
    stu.sex = "ml";  // 使用字符串存储性别
    stu.age = 12;
    stu.weight = 90.54;

    // 输出信息
    cout << stu.name << " " << stu.sex << " " << stu.age << " " << stu.weight << endl;

    return 0;
}
方法3:sex定义char类型,赋值一个字符
#include<bits/stdc++.h>
using namespace std;
struct student{
     string name;
     char sex;  // √
     int age;
     double weight;
};
int main(){
     student stu;
     cin >> stu.name >> stu.sex >> stu.age >> stu.weight;
     cout << stu.name <<  " " << stu.sex <<  " " << stu.age <<  " " ;
     cout << fixed << setprecision(1) << stu.weight << endl;
     return 0;
}
方法4:赋值char数组的办法 cin.get(p1.name, 50);

(1)通过 cin 输入流从键盘读取数据并将其存储到 p1.name 这个变量中,最多读取 50 个字符
(2)用cin.ignore()清除缓冲区中的换行符之后,才可以再次cin.get

#include <iostream>
using namespace std;
struct Person{
    int age;
    char name[50];
};
int main(){
    Person lisa;
    
    char size[12];
    
    lisa.age=15;
    
    cin.get(lisa.name,50);     
    
    // 清除缓冲区中的换行符
    cin.ignore();
    
    cin.get(size,12);
    
    cout << lisa.age;
    cout << lisa.name;
    cout << size;
    
    return 0;
} 

输入结果:
wang
12
输出结果: 
15wang12 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值