2013-11-03 60 views
0

嘗試從鍵盤讀取用戶輸入字符串並將其分配給陣列。 它仍然令人困惑。如何讀取用戶輸入字符串並將其存儲在陣列中

還有什麼想法什麼char ch = 97在這個程序中? 謝謝。

#include<stdlib.h> 

int main() 
{ 
    int i = 0; 
    int j = 0; 
    int count[26]={0}; 
    char ch = 97; 
    char string[100]="readmenow"; 

    for (i = 0; i < 100; i++) 
    { 
     for(j=0;j<26;j++) 
     { 
       if (tolower(string[i]) == (ch+j)) 
       { 
        count[j]++; 
       } 
     } 
    } 
    for(j=0;j<26;j++) 
    { 
     printf("\n%c -> %d",97+j,count[j]); 
    } 
} 
+0

char ch = 97; - 97是'a'的ASCII碼。 – Inisheer

回答

2

讀取用戶輸入做到這一點:

#include <stdio.h> // for fgets 
    #include <string.h> // for strlen 

    fgets(string,sizeof(string),stdin); 
    string[strlen(string)-1] = '\0'; // this removes the \n and replaces it with \0 

確保你正確包括頭

而且ch= 97;同樣是因爲這樣做ch = 'a';

編輯:

scanf是偉大的,只要字符串沒有空間讀取輸入的字符串。 fgets好得多

EDIT 2

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 

int main(){ 

    int i=0,j=0; 

    char input[50]; // make the size bigger if you expect a bigger input 

    printf("Enter string = "); 
    fgets(input,sizeof(input),stdin); 
    input[strlen(input)-1] = '\0'; 

    int count[26]={0}; 

    for (i = 0; i < strlen(input); i++) 
    { 
     for(j=0;j<26;j++) 
     { 
       if (tolower(input[i]) == ('a'+j)) 
       { 
        count[j]++; 
       } 
     } 
    } 
    for(j=0;j<26;j++) 
    { 
     printf("\n%c -> %d",'a'+j,count[j]); 
    } 


    return 0; 
} 

輸出: $ ./test

Enter string = this is a test string 

a -> 1 
b -> 0 
c -> 0 
d -> 0 
e -> 1 
f -> 0 
g -> 1 
h -> 1 
i -> 3 
j -> 0 
k -> 0 
l -> 0 
m -> 0 
n -> 1 
o -> 0 
p -> 0 
q -> 0 
r -> 1 
s -> 4 
t -> 4 
u -> 0 
v -> 0 
w -> 0 
x -> 0 
y -> 0 
z -> 0 
+0

謝謝你,現在清除ch = 97 .. 當從鍵盤不能讀取用戶輸入字符串時,我們使用scanf? – CJM

+0

是的..但scanf將無法正常工作..如果輸入有空格 – sukhvir

+0

好吧..我想要做的是..將代碼行添加到上面的程序來從鍵盤讀取輸入並分配給strring數組並顯示結果。 例如,當我輸入「你今天好嗎」時,只需將它分配給該數組並計算並顯示其中的每個字符。 感謝您的幫助。 – CJM

0
char ch= 97 

這意味着CH = 'A'
它使用ASCII (美國標準信息交換碼)

+0

如果使用「ch = ch + 3」,則會打印'd'。 –

+0

謝謝你。 :-) – CJM

相關問題