2016-06-02 4 views
-3

나는 char * 포인터를 가지고 각 단어의 길이를 계산하려고합니다. 하지만 디버거 (그냥 빈 공간)에서 어떤 결과를 얻고있다. 내가 바꿀지라도 나는 어떤 결과도 얻지 못한다. 코드 :C의 각 단어의 길이를 계산합니다

void wordsLen(char* text, int* words, int n) 
{ 
    int i, count = 0, s = 0; 
    //words[countWords(text)]; // not important 

    for (i=0; i < n; i++) 
    { 
     if (text[i] != ' ') 
     { 
      count++; 

     } 
     else 
     { 
      printf("%d",count); 
     } 
     printf("%d",count);//if I add this it types the count from 1 to the end 
    } 
} 

나는이 배열 삽입하려고 :

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

#define N 100 
void main() 
{ 
    char t[] = "hello my name is."; 
    int cum[N]; 
    wordsLen(t, cum, strlen(t)); 
    getch(); 
} 

어떤 결과를 얻고 있지 않다 것은, 내가 이유를 알고 싶습니다 때문에, 그리고 문제는 길이를 계산하기위한 코드가 단어들? like는 단어의 길이를 세는 것에 좋습니까? 아니면 무언가를 바꿔야합니까?

+0

합니까을 '값을 얻을 wordsLen'을? – Marievi

+0

또한 단어 [countWords (텍스트)];는 무엇입니까? – Marievi

+2

C 또는 C++? 다른 언어가 있습니다 – Garf365

답변

0

다음은 기능을 조금 수정 한 것입니다. 여기

void wordsLen(char* text, int* words, int n) 
{ 
    int i, count = 0, s = 0; 

    for (i=0; i < n; i++) 
    { 
     if (text[i] != ' ') 
     { 
      count++; 
     } 
     else 
     { 
      printf("%d",count); 
      count = 0; 
     } 
    } 
    printf("%d", count); 

}

+0

마지막 단어가 계산되지 않기 때문에 올바르지 않습니다 –

+1

@kevin Wallis 인쇄용 satement를 추가했습니다. 루프가 끝난 후 마지막 단어의 카운팅을 출력합니다 –

0

단어와이 길이 계산에 대한 몇 가지 코드 :

void addWord(int* numberOfWords, int* count) { 
    *numberOfWords = *numberOfWords + 1; 
    *count = 0; 
} 

void print(int numberOfWords, int count) { 
    printf("number of words %d \n", numberOfWords); 
    printf("word length %d \n", count); 
} 

void wordsLen(char* text, int* words, int n) 
{ 
    int i = 0; 
    int count = 0; 
    int numberOfWords = 0; 
    //words[countWords(text)]; // dynamicly set the length 

    for (i = 0; i < n; i++) 
    { 
     char ch = text[i]; 
     if (ch != ' ') 
     { 
      count++; 
     } 

     if (count > 0 && (ch == ' ' || (i == n - 1))) 
     { 
      print(numberOfWords + 1, count); 
      addWord(&numberOfWords, &count); 
     } 
    } 
} 
0

이 시도 :

void wordsLen(char* text, int* words, int n) 
{ 
    int i, count = 0, s = 0; 
    //words[countWords(text)]; // not important 

    for (i=0; i <= n; i++) 
    { 
     if (text[i] != ' ' && text[i] != '\0') 
     { 
      count++; 
     } 
     else 
     { 
      printf("%d ",count); 
      count = 0;    
     } 
     //printf("%d",count); 
    } 
} 
+0

마지막 단어의 카운트를 출력하지 않습니다 –

+0

<= 조건에 해당하는 경우에주의하십시오 – Harsha

관련 문제