2011-10-25 23 views
0

它的功課,對不起。 我不能讓工作計劃在單詞統計字符,對於一個例子:計算選定字的字符數

  • 我輸入字符串:我的名字是彼得
  • 程序會詢問哪個詞來處理..
  • 我進入數量:3
  • 計劃署說:第三字數爲2

#include <stdio.h> 
#include <conio.h> 
#include <string.h> 
int main() 
{ 
    char text[200],vards[20]; 
    int i, length,lengthv, count=0,x; 
    printf("insert txt\n"); 
    gets(text); 
    length=strlen(text); 
    for(i=0; i<length; i++) 
    { 
    if(text[i]!=' ' && text[i]!='.' && text[i]!=',') 
     { 
     printf("%c", text[i]); 
     if (text[i+1]=='\0') 
       count++; 
     } 
    else 
    { 
     if(text[i-1]!=' ' && text[i-1]!='.' && text[i-1]!=',') 
      { 
      count++; 
      printf("\n"); 
      }   
    } 
    } 
    printf("detect lenght of wich name\n"); 
    for(i=0;i<x;i++); 
    scanf("%s", &text); 
    lengthv=strlen(vards); 
    printf("\n The lenght of name is %d", lengthv); 
    getch(); 
    return 0; 
} 
+0

請在發佈前正確地縮進代碼。此外,請描述代碼在實踐中打印的內容,而不是僅僅說「不起作用」。 –

+0

而這段代碼並不是你想要的。 –

+0

你真正的問題是什麼?對於輸入名稱:peter,如果輸入編號爲2,則輸出必須爲2,對於輸入編號3,輸出必須爲1。你的意思是一個字符在一個字符串中出現的次數? – niko

回答

1

我實在無法理解你的代碼,但這裏是我會怎麼做:

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

int main() { 
    char text[200], whichText[200]; 
    int i=0, length, countWord=0, currWord=1, wordChars=0; 

    // Get text input: 
    printf("insert txt\n"); 
    gets(text); 
    length=strlen(text); 

    // Get word to count: 
    while(countWord == 0) { 
    printf("Count which word?\n"); 
    gets(whichText); 
    sscanf(whichText, "%i", &countWord); 
    } 

    // Iterate through each character of the text input: 
    for(i=0; i < length; i++) { 
    // Keep track of which word we are on, by counting spaces: 
    if(text[i] == ' ') { 
     currWord ++; 
     continue; 
    } 
    // While we are on the desired word, count the characters: 
    if(currWord == countWord) 
     wordChars ++; 
    } 

    printf("Count of word %i is %i.\n", countWord, wordChars); 
    return 0; 
} 
+0

感謝男人,對我的錯誤感到遺憾,我病得很重,只是盡力完成我的功課... – eduard

+0

不要擔心它,你必須以某種方式學習。 – Chriszuma