m0_47673309
tumenrjab
2021-01-17 16:06

为什么主函数for循环中的scanf_s语句会报错写入位置时发生访问冲突?

  • c++
  • c语言
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
#include <string>
#include <iostream>
using namespace std;
#define MaxSize 100

//定义员工信息结构体
typedef struct employ
{
	int id;
	char name[50];
	char sex;
	int age;
	float salary;
}Emp;
//定义顺序表
typedef struct sqlist
{
	Emp data[MaxSize];
	int length;
}SqList;
//创建一个含有n个元素的顺序表
void CreatList(SqList*& L, Emp a[], int n)
{
	L = (SqList*)malloc(sizeof(SqList));
	for (int i = 0; i < n; i++)
		L->data[i] = a[i];
	L->length = n;
}
//显示员工信息
void DispList(SqList* L)
{
	for (int i = 0; i < L->length; i++)
		printf("%d,%s,%c,%d,%f\n", L->data[i].id, L->data[i].name, L->data[i].sex, L->data[i].age, L->data[i].salary);
}
//按员工年龄升序显示员工信息,直接插入排序算法(降序)
void InsertSort(Emp R[], int n)
{
	int i, j;
	Emp tmp;
	for (i = 1; i < n; i++)
	{
		if (R[i].age < R[i - 1].age)
		{
			tmp = R[i];
			j = i - 1;
			do
			{
				R[j + 1] = R[j];
				j--;
			} while (j >= 0 && R[j].age > tmp.age);
			R[j + 1] = tmp;
		}
	}
	printf("%d,%s,%c,%d,%f\n", R[i].id, R[i].name,R[i].sex, R[i].age, R[i].salary);
}
//按员工工资降序显示员工信息,采用冒泡排序算法(升序)
void BubbleSort(SqList*& L)
{
	int i, j;
	Emp tmp;
	bool exchange;
	for (i = 0; i < L->length; i++)
	{
		exchange = false;
		for (j = L->length - 1; j > i; j--)
		{
			if (L->data[j].salary > L->data[j - 1].salary)
			{
				tmp = L->data[j];
				L->data[j] = L->data[j - 1];
				L->data[j - 1] = tmp;
				exchange = true;
			}
		}
		if (!exchange)
			break;
	}
	DispList(L);

}
//按员工姓名顺序显示员工信息,采用简单选择排序算法(升序)
void Select(Emp R[], int n)
{
	int i, j, k;
	Emp temp;
	for (i = 0; i < n - 1; i++)
	{
		k = i;
		for (j = i + 1; j < n; j++)
			if (R[j].name < R[k].name)
				k = j;
		if (k != i)
		{
			temp = R[i];
			R[i] = R[k];
			R[k] = temp;
		}
	}

}
void main()
{
	int n;
	int i;
	SqList* L=nullptr;
	Emp e[100];
	for ( i = 0; i < 6; i++)
	{
		scanf_s("%d %s %c %d %f", &e[i].id,&e[i].name,50,&e[i].sex, &e[i].age, &e[i].salary);
	}
	while (1)
	{
		printf("\t\t-----------------------------------------------\n");
		printf("\t\t|            公司员工信息管理系统              |\n");
		printf("\t\t|                    主菜单                    |\n");
		printf("\t\t|            (1)录入员工数据                 |\n");
		printf("\t\t|            (2)显示员工信息                 |\n");
		printf("\t\t|            (3)按员工年龄升序显示员工信息   |\n");
		printf("\t\t|            (4)按员工工资降序显示员工信息   |\n");
		printf("\t\t|            (5)按员工姓名顺序显示员工信息   |\n");
		printf("\t\t-----------------------------------------------\n");
		printf("请选择<1,2,3,4,5,0>:\n");
		scanf_s("%d", &n);
		switch (n)
		{
		case 1:CreatList(L, e, 6); break;
		case 2:DispList(L); break;
		case 3:InsertSort(e, 6); break;
		case 4:BubbleSort(L); break;
		case 5:Select(e, 6); break;
		case 0:exit(0);
		default:; break;
		}
	}
}

 

  • 点赞
  • 回答
  • 收藏
  • 复制链接分享

4条回答