一個密碼的小程式問題
#include <stdio.h>#include <conio.h>
#include <string.h>
int main(void)
{
char pw,pw1;
int x;
printf("Enter password5 characters:\n");
for(x=0;x<5;x++){
pw=getch();
}
pw='\0';
printf("Re-enter your password again:");
for(x=0;x<5;x++){
pw1=getch();
}
pw1='\0';
if(strcmp(pw,pw1))
{
printf("Do not match.\n");
do{
printf("Please enter your password again.\n");
for(x=0;x<5;x++)
{
pw1=getch();
}}while(strcmp(pw,pw1));
}
printf("Your password is %s.\n",pw);
return 0;
}
問題主要在於我的輸入函數得用getch()才行,如果使用getchar(),則很奇怪的,pw() or pw1()中有一個的字串會少或多一個字符,而造成pw pw1二者肯定不同。為何會這樣呢? 本帖最後由 enter 於 2015-2-25 02:42 編輯
#include <stdio.h>
#include <conio.h>
int main(void){
char s,t;
printf("enter password,no more than 5 characters:\n");
gets(s);
while(s) //這裡若用 while(strlen(s)>=5) 則本題ok,所以while(s)有何邏輯上的錯誤呢?
{
printf("too many characters,enter again:\n"); //一旦第一次多於五個字符,後面就算再輸入三個,它也顯示too many。似乎要剛好輸入五個字符才ok。不知是何原因?
gets(s);
}
printf("enter again:\n");
gets(t);
while(strcmp(s,t))
{
printf("not match! enter again:\n");
gets(t);
}
return 0;
} #include <stdio.h>
int main(void){
char pw,pw1;
printf("Please enter your password,no less than 3 and no more than 8 characters:\n");
gets(pw);
while(strlen(pw)<3||strlen(pw)>8)
{
if(strlen(pw)<3)
{
printf("Sorry, too few, try again:\n");
gets(pw);
}
if(strlen(pw)>8)
{
printf("Sorry,too many, try again:\n");
gets(pw);
}
}
printf("Please enter your password again:\n");
gets(pw1);
while(strcmp(pw,pw1) )
{
printf("Sorry, your password not match!\n Re-enter again:\n");
gets(pw1);
}
printf("Your password is %s.\n",pw);
return 0;
} #include <stdio.h>
int main(void)
{
char pw,pw1;
int x;
printf("Please choose your password for 4 to 8 characters, press ENTER to finish:\n");
x=0; \\初始化成0
do{
pw=getch();
printf("*");
x++;
}
while(pw!='\r'); \\因為x已經++到下一個去了。
pw='\0'; \\字串要收尾,否則後面陣列中可能還有其他先前已輸入的值。
while((strlen(pw)<4)||(strlen(pw)>8))
{
while(strlen(pw)>8)
{
printf("Too many, please choose again:\n");
x=0;
do{
pw=getch();
printf("*");
x++;
}while(pw!='\r');
pw='\0';
}
while(strlen(pw)<4)
{
printf("Too few, please choose more:\n");
x=0;
do{
pw=getch();
printf("*");
x++;
} while(pw!='\r');
pw='\0';
}
}
printf("\nPlease re-enter your password:\n");
x=0;
do{
pw1=getch();
printf("*");
x++;} while(pw1!='\r');
pw1='\0';
while(strcmp(pw,pw1)){
printf("Sorry, password nit match.Please enter again:\n");
x=0;
do{
pw1=getch();
printf("*");
x++;} while(pw1!='\r');
pw1='\0';
}
printf("Your password is %s\n",pw);
return 0;
}
頁:
[1]