2016-03-12 3 views
-3

Я пытаюсь напечатать самое длинное слово в строке, но цикл не работает, я не мог найти решение для этого.Печать символа в строке c

char str[50]; 
    int i = 0, count = 0, numOfWords = 0, place; 

    printf("Please enter a sentence: "); 
    gets(str); 

    while (str[i] != '\0') { 
     if (str[i] != ' ') { 
      numOfWords++; 
      if (str[i + 1] == ' ') { 
       if (numOfWords > count) { 
        count = numOfWords; 
        place = i + 1 - numOfWords; 
        numOfWords = 0; 
       } 
      } 
     } 
     i++; 
    } 
    puts(str); 
    printf("%d", count); 
    printf("The word is:\n"); 
    for (i = place; i < numOfWords; i++) 
     printf("%c\n", str[i]); 
    getch(); 
+2

Примечание: Не следует использовать 'получает()', который имеет неизбежный риск переполнения буфера. – MikeCAT

+0

@MikeCAT Я тоже думал. 'gets()' является опасным. – AustinWBryan

+0

Запустите его под отладчиком, шаг за шагом ... –

ответ

1
  • Вы должны использовать count, чтобы определить, сколько раз должен быть принят в последнем цикле.
  • Вы также должны обработать последнее слово.

Попробуйте это:

#include <stdio.h> 
#include <string.h> 

/* This implementation is simple, but maximum readable length is decreased by 1 */ 
char* safer_gets(char* s, size_t max){ 
    char* lf; 
    if (fgets(s, max, stdin) == NULL) return NULL; 
    if ((lf = strchr(s, '\n')) != NULL) *lf = '\0'; /* remove the newline character */ 
    return s; 
} 

int main(void){ 
    char str[51]; 
    int i = 0, count = 0, numOfWords = 0, place = 0; 

    printf("Please enter a sentence: "); 
    safer_gets(str, sizeof(str)); 

    while (str[i] != '\0') 
    { 
     if (str[i] != ' ') 
     { 
      numOfWords++; 
      if (str[i + 1] == ' ' || str[i + 1] == '\0') 
      { 
       if (numOfWords > count) 
       { 
        count = numOfWords; 
        place = i +1- numOfWords; 
        numOfWords = 0; 
       } 
      } 
     } 
     i++; 
    } 
    puts(str); 
    printf("%d", count); 
    printf("The word is:\n"); 
    for (i = 0; i < count; i++) 
     printf("%c", str[place + i]); 
    putchar('\n'); 
    return 0; 
} 
+0

Спасибо за помощь !!! –

Смежные вопросы