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;
}
错误分析:
char[2] sex;
声明了一个长度为 2 的字符数组,这个数组只能存储 2 个字符(包括结尾的空字符\0
)。但是你试图将字符串"ml"
赋给它,这不符合要求,因为"ml"
实际上是一个长度为 3 的字符串(包括结尾的\0
)。
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