0

这是一个家庭作业,对不起。例如,我无法制作用于计算单词中字符的工作程序:

  • 我输入字符串:我的名字是彼得
  • 程序询问要处理哪个单词..
  • 我输入数字: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;
 }
4

1 回答 1

0

我不能真正理解你的代码,但我会这样做:

#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;
}
于 2011-10-25T14:32:12.087 回答