2014-11-02 4 views
-1
#include <stdlib.h> 
#include <stdio.h> 

int main() 
{ 
    unsigned long c; 
    unsigned long line; 
    unsigned long word; 
    char ch; 
    char lastch = -1; 

    c = 0; 
    line = 0; 
    word = 0; 

    while((ch = getchar()) != EOF) 
    { 
     C++; 
     if (ch == '\n') 
     { 
      line ++; 
     } 
     if (ch == ' ' || ch == '\n') 
     { 
      if (!(lastch == ' ' && ch == ' ')) 
      { 
       word ++; 
      } 
     } 
     lastch = ch; 
    } 
    printf("%lu %lu %lu\n", c, word, line); 
    return 0; 
} 

따라서이 프로그램은 표준 입력에서 문자, 줄 또는 단어의 수를 계산합니다. 그러나 요구 사항 중 하나는!, -, + 등의 기호로 구분 된 단어는 2 단어로 간주되어야한다는 것입니다. 그렇게하기 위해 코드를 어떻게 수정합니까?두 단어로 기호로 구분 된 단어 수 계산

+0

에 isalnum() 함수를 사용하여이 숙제인가? –

+1

현재 공백과 개행 문자가 구분 기호로 사용됩니다. 다른 문자로 어떻게 확장할지 생각해보십시오. – mafso

답변

1

단어 분리를 나타내는 문자 배열을 만듭니다. while 루프 내의 두 번째 if 조건을 수정하여 ch가 배열에 있고 lastch가 해당 배열에 없는지 확인합니다.

수정 된 코드 :

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

int main() 
{ 
unsigned long c; 
unsigned long line; 
unsigned long word; 
char ch; 
char lastch = -1; 
int A[256] = {0}; 

//Initialize the array indexes which are to be treated as separators. 
//Next check the presence of any of these characters in the file. 

A[' '] = 1; A['+'] = 1; A['!'] = 1; A['-'] = 1; A['\n'] = 1; 
c = 0; 
line = 0; 
word = 0; 

while((ch = getchar()) != EOF) 
{ 
    C++; 
    if (ch == '\n') 
    { 
     line ++; 
    } 
    if (A[ch] == 1) 
    { 
     if (!(A[lastch] == 1 && A[ch] == 1)) 
     { 
      word ++; 
     } 
    } 
    lastch = ch; 
} 
printf("%lu %lu %lu\n", c, word, line); 
return 0; 
} 
+0

이러한 기호에만 적합합니다. 다른 기호는 어떨까요? ?, @ 등 같이? 그 일을하는 데 더 쉬운 코드가 있습니까? 아니면 모든 단일 기호를 나열해야합니까? – user3880587

0

그냥 다음과 같은 방법

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

int main() 
{ 
unsigned long c; 
unsigned long line; 
unsigned long word; 
char ch; 
char lastch = -1; 

c = 0; 
line = 0; 
word = 0; 

while((ch = getchar()) != EOF) 
{ 
    C++; 
    if(ch=='\n') 
     { 
     line++; 
     continue; 
     } 
    if (!isalnum(ch)) 
    { 
     word++; 
    } 
} 
printf("%lu %lu %lu\n", c, word, line); 
return 0; 
} 
관련 문제