我试图打印字符串中最长的单词,但循环没有运行,我无法找到解决方案。
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();
答案 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;
}