我有這個簡單的問題,從用戶使用函數獲取輸入,然後檢查輸入是否等於「密碼」。然而,strcmp永遠不會返回我想要的值,而罪魁禍首是在我的循環中的某處使用getch()分別獲取每個字符並將它們添加到字符數組中。通過讓printf顯示字符數組,我發現了這一點。如果我輸入密碼,函數會顯示爲密碼「我不知道爲什麼在我輸入的單詞後面的數組中包含了結束雙引號和空格。任何想法?下面是代碼。謝謝。一個簡單的getch()和strcmp問題
#include <stdio.h>
#include <iostream>
#include <conio.h>
#include <string.h>
int validateUser();
int main()
{
for(int x = 0;x<2;x++)
{
if(validateUser())
{
system("cls");
printf("\n\n\t\t** Welcome **"); break;
}
else
{
system("cls");
printf("\n\n\t\tIntruder Alert!");
system("cls");
}
}
system("PAUSE>nul");
return 0;
}
int validateUser()
{
char password[9];
char validate[] = "pass word";
int ctr = 0, c;
printf("Enter password : ");
do
{
c = getch();
if(c == 32)
{
printf(" ");
password[ctr] = c;
}
if(c != 13 && c != 8 && c != 32)
{
printf("*");
password[ctr] = c;
}
c++;
}while(c != 13);
return (!strcmp(password, validate));
}
我看到你已經改變了數組的大小。請您在收到答案後不要這樣做。現在我的回答沒有意義。 – codaddict 2010-09-24 04:57:29
你也改變了'C++'爲'ctr ++',這使得用戶@joshD的答案完全無用。請恢復更改。 – codaddict 2010-09-24 05:03:18
對不起,先生,這些只是錯別字,但我現在將恢復它。 – arscariosus 2010-09-24 05:08:38