O
O
OccamaRazor2016-11-06 15:03:34
Programming
OccamaRazor, 2016-11-06 15:03:34

Correct where wrong, the program gives 1 value less, why?

The program should count the number of words, one when entering "simple example programm" returns the number of words: 2. For any other combinations, it is always less than 1.

char word;
  int count = 0;
  int block = true;
  while ((word = getchar()) != EOF)
  {
    if ( block == false && ((word >= 'A' && word <= 'Z') || (word >= 'a' && word <= 'z')))
    {
      block = false;
      count += 1;
    }
    if (word == ' ' || word == '\n')
      block = false;
    else
    {
      block = true;
      count += 0;
    }
  }
  printf("WORDS:%d\n", count);

Answer the question

In order to leave comments, you need to log in

3 answer(s)
G
GavriKos, 2016-11-06
@OccamaRazor

int block = true; - change this to false. You miss not the last, but the first word. Well bool type is still better ;-)

A
Alexander, 2016-11-06
@NeiroNx

Your last word does not count - because there is no corresponding condition. If block == true && word == EOF then add 1.

M
maaGames, 2016-11-06
@maaGames

Завершайте файл переводом строки, после последнего слова и будет считать правильно. Сейчас ошибка в алкгоритме.
count += 0; - вот это вообще жёстко.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question