代碼中 char *no = { "" }; 定義了指針但未分配指向的內存,隨後 cin >> no[i] 寫入野指針導致崩潰。同時 strcompare 邏輯有缺陷。
char *no = { "" }; // no 是野指針,未指向有效內存
for (int i = 0; i < 25; i++) {
cin >> no[i]; // 寫入非法地址 → 崩潰
}
char *no = new char[25]; // 分配 25 字節
// 使用後釋放
delete[] no;
char no[25] = {0}; // 自動初始化為 0,無需手動管理
// 直接用 no 作為字符數組
char a;
char *no = &a; // 只能存 1 個字符,不能存字符串
int strcompare(const char *ch1, const char *ch2) {
// 使用標準庫 strcmp,安全且正確
return strcmp(ch1, ch2) == 0;
// 或手寫:逐字符比較直到 '\0'
for (int i = 0; ; i++) {
if (ch1[i] != ch2[i]) return 0;
if (ch1[i] == '\0') return 1; // 都結束且相等
}
}
#include <iostream>
#include <cstring>
#include <ctime>
#include <windows.h> // Sleep
using namespace std;
int strcompare(const char *ch1, const char *ch2) {
return strcmp(ch1, ch2) == 0;
}
int main() {
char no[25] = {0}; // 棧上分配,自動初始化
cout << "請輸入 24 字符時間字符串 (如 Tue Nov 22 18:29:30 2016): ";
cin.getline(no, 25); // 安全讀取整行
while (true) {
time_t now = time(0);
char *dt = ctime(&now); // 格式: "Tue Nov 22 18:29:30 2016\n"
dt[strlen(dt)-1] = '\0'; // 去掉換行符
if (strcompare(dt, no)) {
for (int i = 0; i < 20; i++) {
Sleep(1000);
cout << "\a"; // 蜂鳴
}
break; // 匹配後退出,或去掉 break 持續監控
}
Sleep(1000); // 每秒檢查一次,避免佔用 CPU
}
return 0;
}
char no[25] 替代野指針。cin.getline 讀取整行,避免 cin >> 遇空格截斷。strcmp 比較字符串,自動處理結束符。Sleep 降低 CPU 佔用。