1. 程式人生 > >c語言程式設計:用strcpy比較陣列(銀行卡密碼程式設計),strcpy(複製陣列內容)和getchar()(敲鍵盤字元,統計不想要的字元的個數)

c語言程式設計:用strcpy比較陣列(銀行卡密碼程式設計),strcpy(複製陣列內容)和getchar()(敲鍵盤字元,統計不想要的字元的個數)

統計從鍵盤輸入一行字元的個數:

 

 1 //用了getchar() 語句
 2 //這裡的\n表示回車
 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 int main()
 4 {
 5     int n = 0;
 6     printf("輸入鍵盤上的字元\n");
 7     while (getchar() !='\n'){
 8         n++; 
 9     }
10     printf("%d\n", n);
11     system("pause");
12     return
0; 13 }

 

 

 


 

 

 

//更改題目:輸入一行字元,直到輸入9為止,並統計輸入的個數


//當你輸入一行字元如果第一個就為9的話,那麼打印出來i的值結果為0,因為當迴圈判斷到9的時候已經跳出,統計結果就是0
//當你輸入了一行字元沒有9的時候,鍵入回車鍵,仍然打印不出來i的結果,因為while迴圈一直在迴圈無法跳出,回車鍵仍然算做鍵入的字元,有幾個算幾個
//直到你打出來9為止,統計輸入的字元(包括回車鍵)的個數,即為i的值

 

 1 #include<stdio.h>
 2 #include<stdlib.h>
 3
int main (){ 4 int i = 0; 5 while (getchar() != '9'){ 6 i++; 7 } 8 printf("該系列字元不等於9的個數是\n%d\n", i); 9 system("pause"); 10 return 0; 11 }

 

 

1-8加回車鍵,不等於9的鍵一共有九個

 


 

 

 

//再次更改題目:輸入一行字元,直到輸入9為止,並統計輸入的個數
//值得注意的是,換位思考,作為使用者的他們並不想看到輸入無限個不含9的字元仍然挑不出結果


//這時,我們加一個if語句,當i加到10(輸入的10個鍵仍然不包含'9'的時候),則用break語句跳出,若小於10個數字包含9則退出,並列印不為9的個數。

 

 

 1 #include<stdio.h>
 2 #include<stdlib.h>
 3 int main(){
 4     int i = 0;
 5     while (getchar() != '9'){
 6         i++;
 7         if (i == 10){
 8             printf("輸入過多\n");
 9             break;
10         }
11     }
12     if (i != 10){
13 
14 
15         printf("該系列字元不等於9的個數是\n%d\n", i);
16     }
17     system("pause");
18     return 0;
19 }

 


 

 

 

//字串內容之間的複製,採用strcpy函式,需要呼叫<string.h>函式庫
//strcpy(a,c)
//順便再次提一下關於陣列中括號裡面填數字的問題,例如 arr[]="hi" ,中括號內應該填3或者選擇不填,當然不填比較省事
//為什麼會多一個數?因為還有個結束符\0,也要佔一個記憶體空間,但是計算長度(strlen(arr[]))的時候結果還是為2,sizeof時結果為3.
//關於陣列這個點需要謹記,比較容易遺忘。

 

 1 #define _CRT_SECURE_NO_WARNINGS
 2 #include <stdio.h>
 3 #include <stdlib.h>
 4 #include<string.h>
 5 int main()
 6 {
 7     char a[] = "hi", c[] = "i am teacher!";
 8     strcpy(c,a);
 9     printf("%s\n%s\n", a, c);
10     system("pause");
11     return 0;
12 }

 

 

 


 

 

 

//// 設計程式:銀行卡密碼輸入

 

//用了strcmp函式,呼叫標頭檔案為<string.h>
//題中不可以寫成if(strcmp password==100001),因為c語言不支援這種寫法,通過陣列比較,當password陣列中的值
//小於100001時,==後應為負數,反之大於時為正數
//c語言中strcmp這種比較方法可概括為"查英文詞典法"

 

 

 1 #define _CRT_SECURE_NO_WARNINGS
 2 #include<stdio.h>
 3 #include<stdlib.h>
 4 #include<string.h>
 5 int main(){
 6     int i;
 7     char password[10] = { 0 };
 8     for (i = 1; i <= 3; i++){
 9         printf("請輸入密碼\n");
10 //        字元陣列,scanf時候可以不加&
11         scanf("%s", &password);
12         if (strcmp(password, "100001") == 0){
13             printf("輸入正確!\n");
14             printf("正在登陸...\n");
15             break;
16         }
17         else{
18             printf("輸入錯誤,請重試\n");
19             if (i == 3){
20                 printf("重複輸入過多,退出登入\n");
21             }
22         }
23     }
24     system("pause");
25     return 0;
26 }