看板 C_and_CPP 關於我們 聯絡資訊
剛接觸C++,老師出了一題練習題「自動櫃員機的密碼輸入」, 。判斷是否有輸入密碼 。密碼為數字,四到十二位數 。預設密碼作為比對 。輸入密碼與預設密碼作比對 。正確,印出「歡迎使用」字串 。錯誤,要求重新輸入 。輸入錯誤超過三次則印出錯誤訊息,按下任意鍵關閉 以上要求基本上都可以成功寫出,唯獨第二項「密碼限制四到十二位數」, 想不出來,希望C++板的鄉民可以幫幫我,提示一下該如何完成要求。 這是我想很久才寫出的,不過一下就被點出瑕疵, 想是密碼開頭為0或者錯誤位數測試時,輸入1111111111111(13個1), 可以正確偵測出為輸入位數錯誤,但輸入2222222222222(13個2或3.4.5...等), 就會變成密碼錯誤而已。 #include <stdio.h> #include <stdlib.h> int main( void ) { int input; int password; int counter; counter = 1; password = 9527; while( counter <= 3 ) { printf( "Please Enter Your Password:"); scanf( "%d" , &input ); if( input > 999 && input < 1000000000000 ) { if( input == password ) { printf( "Welcome To Use" ); break; } else { printf( "Wrong Word\n" ); counter += 1; } } else { printf( "Wrong Word Count\n" ); counter += 1; } } if( counter == 4 ) { printf( "Please Try Again Later" ); } system( "pause" ); return 0; } -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 120.113.127.195
purpose:scanf("%s" , &inputstr ); 03/26 00:01
LPH66:這個題目在告訴你不要把所有看起來像數字的東西用數字型態存 03/26 01:15
leiyan:老師沒教string嗎? 03/26 02:56
string最近才要開始講。 我照一樓的把程式修改一下後,變得更奇怪@@, 其中「 input.size() > 3 && input.size() < 13 」這段, 我不知道能不能這樣用,這是我自己腦補的, 還有,程式執行結束後會出現「於 0x578dad4a (msvcp100d.dll) 的 ATMpassword-update.exe 中發生未處理的例外狀況 : 0xC0000005: 讀取位置 0x30303034 時發生存取違規」, 這好像是把scanf修改成( "%s", &input )後才出現的。 #include <cstdio> #include <stdlib.h> #include <iostream> #include <string> using namespace std; int main( void ) { string input; string password; int counter; password = 9527; counter = 1; while( counter <= 3 ) { printf( "Enter:" ); scanf( "%s", &input ); if( input.size() > 3 && input.size() < 13 ) { if( input == password ) { printf( "Welcome" ); break; } else { printf( "Wrong\n" ); counter = counter + 1; } } else { printf( "Wrong Count\n" ); counter = counter + 1; } } if( counter == 4 ) { printf( "Error" ); } system( "pause" ); return 0; } ※ 編輯: sofksjmf 來自: 120.113.127.195 (03/26 13:16)
linotwo:這種寫法是 C++ string 你還是先學會用 C-style string 吧 03/26 14:01
linotwo:像 char input[256] 這種的 03/26 14:02
linotwo:如果要取得長度就是用 strlen(input) 03/26 14:02
目前程式大致上是完成了(字數判斷,密碼判斷,錯誤三次關閉), 不過還剩下一個地方我解不開,就是原本輸入正確密碼會進入歡迎畫面, 但是現在輸入正確密碼,他還是顯示密碼錯誤,那邊幾乎沒有改動到, 卻無法正確使用,可以幫我看看到底哪邊出錯了嗎?整個程式就只差那部分>< #include <cstdio> #include <stdlib.h> #include <iostream> #include <string> using namespace std; int main( void ) { char input[256]; char password[256] = "9527"; int counter = 1; while( counter <= 3 ) { printf( "Enter:" ); scanf( "%s", &input ); if( input == password ) { printf( "Welcome" ); break; } else if( strlen(input) > 3 && strlen(input) < 13 ) { printf( "Wrong\n" ); counter = counter + 1; } else { printf( "Wrong Count\n" ); counter = counter + 1; } } if( counter == 4 ) { printf( "Error" ); } system( "pause" ); return 0; } ※ 編輯: sofksjmf 來自: 120.113.127.195 (03/26 14:43) ※ 編輯: sofksjmf 來自: 120.113.127.195 (03/26 14:45)
esnjd:問題就出在著色那一行,拿兩個陣列位置來比當然不符合 03/26 15:28
linotwo:字串比對可以用 strcmp 03/26 15:46
linotwo:回傳 0 表示相等 03/26 15:47
謝謝各位的幫忙,這練習題已經完成了。^_^ ※ 編輯: sofksjmf 來自: 120.113.127.195 (03/26 23:37)