+ 1
Code coach: vowel counter
My code outputs 1 for any input that is taken and I'm not able to figure out what error i made, please help Here goes my code: #include <stdio.h> int main() { char vowel[11]={'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U' }; char s[500];int i=0,count=0; scanf("%s",s); while(s[i]!='\0') { for(int j=0;j<11;j++) { if(s[i]==vowel[j]) count++; } i++; } printf("%d",count); return 0; } I also tried by initialising: vowel[11]={"aeiouAEIOU"};
3 Antworten
+ 7
The code works okay if the input has no spaces.
Instead of: This is the day
Output: 1
Enter: Thisistheday
Output: 4
Using "%s" in scanf only reads characters up to a space or a newline. It reads the next word as a separate string.
To read the whole line you can use this arcane format specifier: "%[^\n]"
It says to read everything from the beginning of the line (symbolized by ^) to the newline (\n). Beware that this will leave the newline in the input buffer. You would need to deal with that if expecting multiple input lines.
Another way is to use fgets(s, 500, stdin); to read the whole line. That includes the newline, which you might not want, but it does no harm in this case.
The vowel array needs to be only 10 characters. The inner loop should test for j<10. As it is, the loop tests the item at 10, which is past the given vowel characters and implicitly filled in as a 0 by the compiler.
Final note: Trying {"aeiouAEIOU"} ends up wrongly storing a string pointer in the char array; not the letters.
+ 2
Sanjana you are welcome!
+ 1
Brian thank you very much!!