#include<stdio.h> int main() { char commandA[5]; char option[4]; printf("Input string:\n"); scanf_s("%s",commandA,(unsigned int)sizeof(commandA)); printf("%s\n", commandA); printf("Input second string:\n"); scanf_s("%s", option, (unsigned int)sizeof(option)); printf("%s\n", option); return 0; }
代碼如上,如果commandA輸入的長度超過定義的長度減一的時候,就會讀取字符串異常。
謹記定義好字符串的長度。可以對scanf_s的返回值進行判斷。