2011-05-12 15 views
1

可能重複:
c program for 20 chars and reports quantity of each[SOLVED]創建一個讀取字符串並指出每次字符發生次數的C程序?

這是我到目前爲止所。但是,當我使用該程序並說我輸入「qwerty」時,它只是說我已經使用過5次Q.請幫忙。

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

void readData(char line[], int size) 
{ 
    printf("Enter a string no longer than 20 characters: "); 
    fgets(line, size, stdin); 
    line[strlen(line) - 1] = '\0'; 
    strupr(line); 
    printf("You Entered %s\n", line); 
    return; 
} 

void counter(char line[], int counts[]) 
{ 
    int i; 
    char c; 
    for (i = 0; i < strlen(line); i++) 
    { 
     c = *line; 
     if (c >= 'A' && c <= 'Z') 
     { 
      counts[c - 'A']++; 
     } 
     else 
     { 
      counts[26]++; 
     } 
    } 
    return; 
} 

void printer(int counts[]) 
{ 
    int i; 
    for (i=0; i < 26; i++) 
    { 
     printf("there are %d occurances of %c\n", counts[i], i + 'A'); 
    } 
    printf("there are %d occurances of non alphabetic\n", counts[26]); 
    return; 
} 

int main() 
{ 
    const int SIZE = 22; 
    char line[22] = {'\0'}; 
    int counts[27] = { 0 }; 
    readData(line, SIZE); 
    counter(line, counts); 
    printer(counts); 
    return(0); 
} 
+0

你能格式化它,所以它是可讀的嗎?使用Blockquote功能。 – 2011-05-12 15:03:23

+0

soz爲你編輯 – killerbill09 2011-05-12 15:06:29

+1

[創建一個讀取20個字符的字符串並指出每個字符出現的次數的C程序的完全重複](http://stackoverflow.com/questions/5975413/create-ac-程序在一個字符串中讀取20個字符和狀態多麼多)和[C編程問題?](http://stackoverflow.com/questions/5978708/c-編程問題) – 2011-05-12 15:29:17

回答

3

的問題是:

c=*line; 

,因爲它總是字符串的第一個字符。嘗試將其更改爲:

c=line[i]; 
+0

ty我使用上面的一個,但這也工作ty。 – killerbill09 2011-05-12 15:15:28

2

的問題是在這裏:

c = *line; 

這使得c總是在輸入,這是第一信爲什麼你看到Q 5作爲輸出,當你進入qwerty

將其更改爲:

c = *(line+i); 

這使得c具有輸入字符串的i個字符。

+0

Ty解決了非常感謝:D – killerbill09 2011-05-12 15:12:35

相關問題