打印字符串中的字符c

时间:2016-03-12 12:48:15

标签: c visual-studio

我试图打印字符串中最长的单词,但循环没有运行,我无法找到解决方案。

    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();

1 个答案:

答案 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;
}