Программа, которая считает символы выбранного слова - PullRequest
0 голосов
/ 25 октября 2011

Это домашнее задание, извините за это.Я не могу создать рабочую программу для подсчета символов в слове, например:

  • Я ввожу строку: Меня зовут Питер
  • Программа спрашивает, какое слово обрабатывать ..
  • Я ввожу число: 3
  • Программа говорит: Количество Третьего слова равно 2.

#include <stdio.h>
#include <conio.h>
#include <string.h>
int main()
{
  char text[200],vards[20];
  int i, length,lengthv, count=0,x;
  printf("insert txt\n");
  gets(text);
  length=strlen(text);
  for(i=0; i<length; i++)
   {
    if(text[i]!=' ' && text[i]!='.' && text[i]!=',')
      {
        printf("%c", text[i]);
      if (text[i+1]=='\0') 
              count++;
      }
   else
     {
        if(text[i-1]!=' ' && text[i-1]!='.' && text[i-1]!=',')
          {
            count++;
            printf("\n");
          }          
     }
   }
  printf("detect lenght of wich name\n");
  for(i=0;i<x;i++);
  scanf("%s", &text);
  lengthv=strlen(vards);
  printf("\n The lenght of name is %d", lengthv);
  getch();
  return 0;
 }

1 Ответ

0 голосов
/ 25 октября 2011

Я не совсем понимаю ваш код, но вот как я это сделаю:

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

int main() {
  char text[200], whichText[200];
  int i=0, length, countWord=0, currWord=1, wordChars=0;

  // Get text input:
  printf("insert txt\n");
  gets(text);
  length=strlen(text);

  // Get word to count:
  while(countWord == 0) {
    printf("Count which word?\n");
    gets(whichText);
    sscanf(whichText, "%i", &countWord);
  }

  // Iterate through each character of the text input:
  for( i=0; i < length; i++ ) {
    // Keep track of which word we are on, by counting spaces:
    if( text[i] == ' ' ) {
      currWord ++;
      continue;
    }
    // While we are on the desired word, count the characters:
    if( currWord == countWord )
      wordChars ++;
  }

  printf("Count of word %i is %i.\n", countWord, wordChars);
  return 0;
}
...