我正在嘗試檢查用戶輸入的輸入中是否存在所有大寫字母。
我嘗試創建一個包含 26 個值的陣列,0 代表 A,25 代表 Z。起初我將這些值初始化為 0。
之后我要求用戶輸入,然后我檢查它是否與 ASCII 匹配。如果是,我將陣列值更改為 1。
之后,我確保所有陣列值都是 1;如果是,所有字母都在輸入中。
我假設用戶將以 0 結束輸入。
輸入是“Q$@UICK BROWN FOX JUMPS OVER THE LAZY DOG!0”。
這是代碼:
#include <stdio.h>
int main()
{
int z;
int x = 1;
int arr[26] = {0};
printf("enter a sentance to check if all latter in ABC are in the sentance (in upper case):\n");
while (x!=0) {
scanf(" %d", &x);
z = x - 65;
if (z>=0 && z<=25) {
arr[z]=1;
}
}
z=0;
while (arr[z]==1 && z<26) {
z;
if (z==26) {
printf("all the ABC in ur sentance\n");
break;
}
}
printf("all the ABC does not in ur sentance\n");
return 0;
}
沒有輸出,我認為是因為scanf有問題,但我不知道如何解決。
uj5u.com熱心網友回復:
%d格式說明符scanf()用于讀取整數,而不是字符。在這種情況下,您應該使用getchar()而不是scanf()逐個讀取字符。- 該字符
0沒有值 0。(在 ASCII 中為 48)。 - 像這樣使用幻數
65并不好。在這種情況下,使用類似的字符常量'A'應該可以使含義清晰。
那個部分
while (x!=0) {
scanf(" %d", &x);
z = x - 65;
if (z>=0 && z<=25) {
arr[z]=1;
}
}
應該:
while ((x = getchar()) != '0' && x != EOF) {
z = x - 'A';
if (z>=0 && z<=25) {
arr[z]=1;
}
}
另請注意,"all the ABC does not in ur sentance\n"即使在列印后"all the ABC in ur sentance\n"也會列印。您應該使用return 0;而不是break;完成函式的執行并防止輸出額外的字串。
uj5u.com熱心網友回復:
您需要使用%c來讀取一個字符并將其轉換為它的字符代碼。%d讀取整數的表示。
如果字符0結束輸入,則需要與 比較'0',而不是0。
您可以使用它isupper()來測驗字符是否為大寫字母,而不是自己測驗范圍。
檢查所有字符是否已輸入的回圈可以簡化如下所示。
#include <stdio.h>
#include <ctype.h>
int main()
{
int z;
char x;
int arr[26] = {0};
printf("enter a sentance to check if all latter in ABC are in the sentance (in upper case):\n");
while (1) {
scanf(" %c", &x);
if (x == '0') {
break;
}
if (isupper(x)) {
z = x - 'A';
arr[z]=1;
}
}
for (z = 0; z < 26; z ) {
if (arr[z] == 0) {
printf("all the ABC are not in your sentance\n");
return 0;
}
}
printf("all the ABC in your sentance\n");
return 0;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/485091.html
標籤:C
上一篇:這個工會合法嗎?
