Próbowałem ostatnio wrócić do C (w celach związanych z pracą) i byłem na warsztacie odświeżającym C. Nie mogę się zastanowić, dlaczego w tym kodzie występuje nieskończona pętla.
Próbuję napisać kod programu, który zwraca liczbę słów w tablicy znaków. Każda pomoc byłaby bardzo mile widziana. Dzięki!
// ArrayWords.c
#include <stdio.h>
#include <ctype.h>
#define LENGTH 50
int word_count(char []);
int main(void) {
char sentence[LENGTH];
int i;
printf("Enter a sentence with at most %d characters:n", LENGTH);
for(i = 0; i < LENGTH; i++)
scanf("%s", &sentence[i]);
printf("Sentence = %sn", sentence);
printf("Word count = %dn", word_count(sentence));
return 0;
}
// Count the number of words in str
int word_count(char str[]) {
int i, word = 1;
for(i = 0; i < LENGTH; i++)
while(str[i] != " ")
if((isspace(str[i])))
{
word++;
}
return word;
}
Odpowiedzi:
1 dla odpowiedzi № 1- Twoje użycie
scanf
nie jest dobrze. word_count
powodują nieskończoną pętlę, ponieważi
nie jest aktualizowany wwhile
pętla.
poprawiony kod:
// ArrayWords.c
#include <stdio.h>
#include <ctype.h>
#define LENGTH 50
int word_count(char []);
int main(void) {
char sentence[LENGTH];
printf("Enter a sentence with at most %d characters:n", LENGTH);
fgets(sentence, sizeof(sentence), stdin);
printf("Sentence = %sn", sentence);
printf("Word count = %dn", word_count(sentence));
return 0;
}
// Count the number of words in str
int word_count(char str[]) {
int i = 0, word = 1;
while(str[i] != " ") {
if((isspace(str[i])))
{
word++;
}
i++;
}
return word;
}
0 dla odpowiedzi nr 2
for(i = 0; i < LENGTH; i++)
scanf("%s", &sentence[i]);
Tutaj czytasz char
jeden po drugim. tak powinno być %c
, lubić scanf(" %c", &sentence[i]);
Nie będzie to jednak właściwy sposób na odczytanie ciągu. Ponieważ nie będzie to położyć