所以我从c和c ++开始,我在结构,我已经为员工做了一个结构,定义了员工的数量,并做了两个功能:1填写员工信息,1到打印出来:
#include <iostream>
#include <cstdio>
#include <stddef.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define NO 3
using namespace std;
struct employee {
char fName[15];
char lName[15];
unsigned int age;
char gender;
bool married;
char Pp[5];
};
typedef struct employee Employee;
void fillEmployeeDetails(Employee * const employeePtr);
void printEmployeeDetails(const Employee * const employeePtr);
int main(){
Employee Employees[NO];
fillEmployeeDetails(Employees);
printEmployeeDetails(Employees);
//printf("%s",&(Employees[0].Pp));
return 0;
}
void fillEmployeeDetails(Employee * const employeePtr){
char marriageStatus;
int i;
for(i = 0; i < NO + 1; ++i){
marriageStatus = '\0';
system("CLS");
printf("No. of employees: %d\n\n", NO);
printf("Employee No. %d:\n\n", i+1);
printf("First name: ");
scanf("%14s", employeePtr[i].fName);
printf("Last name: ");
scanf("%14s", employeePtr[i].lName);
printf("Age: ");
scanf("%u", &(employeePtr[i].age));
while(employeePtr[i].age > 150 || employeePtr[i].age < 0){
printf("Age: ");
scanf("%u", &(employeePtr[i].age));
}
while(employeePtr[i].gender != 'M' && employeePtr[i].gender != 'F' ){
printf("Gender: ");
scanf("%s", &(employeePtr[i].gender));
employeePtr[i].gender = toupper(employeePtr[i].gender);
}
while(marriageStatus != 'Y' && marriageStatus != 'N'){
printf("Married?(Y/N): ");
scanf("%s", &marriageStatus);
marriageStatus = toupper(marriageStatus);
if(marriageStatus == 'Y' && employeePtr[i].gender == 'F'){
employeePtr[i].married = true;
strcpy(employeePtr[i].Pp, "Mrs.");
}
else{
if(marriageStatus != 'Y' && employeePtr[i].gender == 'F'){
strcpy(employeePtr[i].Pp, "Miss");
}
else{
strcpy(employeePtr[i].Pp, "Mr.");
}
}
}
}
}
void printEmployeeDetails(const Employee * const employeePtr){
system("CLS");
for(int i = 0; i < NO; ++i){
printf("Employee No.: %d\n\nName: %s %s %s\nAge: %u\nGender: %c\n\n\n",i,employeePtr[i].Pp,employeePtr[i].fName,employeePtr[i].lName,employeePtr[i].age,employeePtr[i].gender);
}
}
我在
的函数fillEmployeeDetails中遇到了问题scanf("%s", &marriageStatus);
这一行将我的i(如果i =&gt; 1)更改为0,任何帮助都将不胜感激。
答案 0 :(得分:1)
您已将marriageStatus
声明为char
类型。对scanf("%s", &marriageStatus);
的调用会覆盖相邻的内存区域,因为marriageStatus只能容纳1个字符。
尝试将声明替换为:
char marriageStatus[10];
请注意,程序将因输入大于9而崩溃(为NULL字节留出空间),因此您需要将scanf调用替换为:scanf("%9s", marriageStatus);
如果您没有指定要读取的字符数,则会在程序中创建大量安全漏洞。
编辑:实际上看一下代码,看起来你真的希望weddingStatus成为一个char,在这种情况下,你想要scanf(" %c", marriageStatus);
已经指出过了。
如果你被期待要么&#39; Y&#39;或者&#39; N&#39;,您可能需要检查它是否已正确读取。