scanf_s()讀入字符串和數字

擬解決問題描述如下:

(以錄入學生信息爲列)

1. 從鍵盤輸入要錄入的學生個數

2. 輸入學生的姓名(字符串)、數學成績(數字)、語文成績(數字)


問題解的關鍵:在輸入姓名(字符串)、數學成績(數字)、語文成績(數字)時,採用如下方式,會出現訪問衝突報錯:

   scanf_s("%s %d %d", st[i].name, &st[i].math, &st[i].chinese);

究其原因還是在於scanf_s函數,在輸入字符串的時候一定要限定輸入字符串的長度,修改成如下代碼即可解決問題:

scanf_s("%s", st[i].name, NAME_LEN); 
scanf_s("%d %d", &st[i].math, &st[i].chinese);

完成代碼如下:

#include <stdio.h>
#include <stdlib.h>

#define NAME_LEN  50

typedef struct student
{
	char name[NAME_LEN];
	int chinese;
	int math;
}student;

int main()
{
	student *st = NULL;
	int i = 0, n = 0;

	printf("請輸入學生個數\n");
	scanf_s("%d", &n);
	st = (student*)malloc(n * sizeof(student));
	
	printf("請輸入學生的姓名 數學成績 語文成績:\n");
	for (i = 0; i < n; i++){
		scanf_s("%s", st[i].name, NAME_LEN); //關鍵在這裏,沒有NAME_LEN會報錯
		scanf_s("%d %d", &st[i].math, &st[i].chinese);
	}
	for (i = 0; i < n; i++)
		printf("%s 數學成績:%d  語文成績:%d\n", st[i].name, st[i].math, st[i].chinese);
	free(st);
	return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章