2016-12-17 9 views
1

私の文章の見た目にかかわらず、単語、文字、改行の数を数えたいと思います。 (:純粋なCで単語、文字、行の数を数える方法

y yafa \n \n youasf\n sd

は、プログラムがまだ正しく単語、行、文字の数をカウントすることができるはずです例えば、私はこのような文を入力した場合でも)。私は純粋なCでこのようなプログラムを実装する方法を知らない、誰でも私を助けることができますか?あなたはピュアCではなく、むしろC++で書いていません。ここ

は私の現在のコードであり、それは特定の条件下でのみ正しいことができます...

int main() { 
    int cCount = 0, wCount = 0, lCount = 0; 

    printf("Please enter the sentence you want\n"); 

    char str[20]; 
    int j7 = 0; 

    while (int(str[j7]) != 4) { 
     str[j7] = getchar(); 
     if (str[0] == ' ') { 
      printf("Sentence starts from a word not blank\n"); 
      break; 
     } 
     if (int(str[j7]) == 4) 
      break; 
     j7++; 
    } 
    int count = 0; 
    while (count < 20) { 
     if (str[count] != ' ' && str[count] != '\n') { 
      cCount++; 
     } else 
     if (str[count] == ' ') { 
      wCount++; 
     } else 
     if (str[count] == '\n') { 
      lCount++; 
     } 
     count++; 
    } 

    printf("Characters: %d\nWords: %d\nLines: %d\n\n", 
      cCount, wCount++, lCount + 1); 
    int x = 0; 
    std::cin >> x; 
} 
+8

'純粋なC 'がありません。 'std :: cin'なので、C++と混同しないでください – artm

+2

また、何も意味しない' j7'ではなく、良い変数名を使うようにしてください – artm

+1

あなたのコードを見直すには、http ://codereview.stackexchange.com/ –

答えて

2

あなたの目標を達成するために、あなたは論理的な一連の手順に問題をまとめる必要があります。各文字の

  • 読み:
    • 前の1は、行区切りがある場合、あなたは新しいを持っていますライン;
    • 前の単語が単語区切り文字であり、現在の単語がない場合は、新しい単語があります。
    • すべての場合、新しい文字がある場合は、次の繰り返しの前の文字として保存します。

last文字の初期値は、それが空白でない場合、任意の新しいラインと、おそらく新しい単語を開始した場合読んで最初の文字として使用'\n'。ここで

は、単純な実装です:

#include <ctype.h> 
#include <stdio.h> 

int main(void) { 
    long chars = 0, words = 0, lines = 0; 

    printf("Enter the text:\n"); 

    for (int c, last = '\n'; (c = getchar()) != EOF; last = c) { 
     chars++; 
     if (last == '\n') 
      lines++; 
     if (isspace(last) && !isspace(c)) 
      words++; 
    } 
    printf("Characters: %ld\n" 
      "Words: %ld\n" 
      "Lines: %ld\n\n", chars, words, lines); 
    return 0; 
} 

あなたがwhileループを使用する必要がある場合は、forループはこのように変換することができます:

#include <ctype.h> 
#include <stdio.h> 

int main(void) { 
    long chars = 0, words = 0, lines = 0; 
    int c, last = '\n'; 

    printf("Enter the text:\n"); 

    while ((c = getchar()) != EOF) { 
     chars++; 
     if (last == '\n') 
      lines++; 
     if (isspace(last) && !isspace(c)) 
      words++; 
     last = c; 
    } 
    printf("Characters: %ld\n" 
      "Words: %ld\n" 
      "Lines: %ld\n\n", chars, words, lines); 
    return 0; 
} 
+0

@ 4386427:実際には、 'two \ nwords'は' wc': '1 2 9'の出力よりも間違いなく正しい9文字、2単語、2行として数えられます。 – chqrlie

+0

whileループを使うことができますか?..... –

+0

@ D.Kenny: 'for'ループをエラーが発生しやすい' while'ループに変換しました。 – chqrlie

関連する問題