The task is to: Write a program, which for the entered line determines the number of words and displays each word on a separate line and its length. I wrote a program that counts words and translates each into a new line. How to implement the calculation of the length of characters in each line? I know that through strlen, but I don’t understand where exactly to use this function. Here is my code:

#include <stdio.h> #include <string.h> #define IN 1//внутри слова #define OUT 0// снаружи слова #define PR printf int main() { char buf[256] = { 0 }; int flag = OUT; int i = 0; int count = 0; int word = 0; PR("Enter a line ,please:\n"); fgets(buf, 512, stdin); buf[strlen(buf) - 1] = ' ';//удаление \n while (buf[i]) { if (buf[i] != ' ' && flag == OUT) { count++; flag = IN;//вошли в слово putchar(buf[i]); } else if (buf[i] != ' '&& flag == IN) { putchar(buf[i]);//внутри слова } else if (buf[i] == ' '&& flag == IN) { flag = OUT;//вышли из слова putchar('\n'); } i++; } putchar('\n'); PR("%d words\n", count); return 0; } 
  • 2
    get a counter that zeroes when you enter a word, increase the words inside and output when you exit - Mike

1 answer 1

 int countSymbolsCurrentWord = 0; while (buf[i]) { if (buf[i] != ' ' && flag == OUT) { count++; flag = IN;//вошли в слово putchar(buf[i]); } else if (buf[i] != ' '&& flag == IN) { putchar(buf[i]);//внутри слова countSymbolsCurrentWord++; // увеличиваем кол-во символов на один } else if (buf[i] == ' '&& flag == IN) { printf("%s %d\n", " ;count symbols: ", countSymbolsCurrentWord); // выводим на экран + переходим на новую строку countSymbolsCurrentWord = 0; // и обнуляем, т.к. количество символов в слове получено flag = OUT;//вышли из слова } i++; }