#include <stdio.h>
#include <string.h>
void vowel_check(char message[30], int i);
int main() {
char message[30];
while (fgets(message, 15, stdin) != NULL) {
int i = 0;
while (i < 30) {
vowel_check(message, i);
i ;
}
printf("%s\n", message);
}
}
void vowel_check(char message[30], int i) {
if (message[i] == 'a'
|| message[i] == 'e'
|| message[i] == 'i'
|| message[i] == 'o'
|| message[i] == 'u') {
message[i] = '\0';
i ;
}
}
So it was my first time learning strings, and I want to make a program that gets rid of all the vowels in the program.
ex) white milk -> wht mlk
I think I'm not stuck in something massive and extremely challenging, I think I didn't get the hang of strings just yet. Can anyone point out what part of my code I did wrong? Thanks!
CodePudding user response:
You declared a character array with 30
elements
char message[30];
but in the call of fgets
you are using the magic number 15
by an unknown reason
while (fgets(message, 15, stdin) != NULL) {
The user can enter a string that contains even much less than 15
symbols. In this case this while loop
while (i < 30) {
vowel_check(message, i);
i ;
}
invokes undefined behavior.
Also changing a vowel to the zero character
message[i] = '\0'
does not remove the element that contained a vowel from the string.
And this statement within the function
i ;
has no effect.
It seems you need to write a function that will remove vowels from a string.
Here is a demonstration program that shows how such a function can be written.
#include <string.h>
#include <stdio.h>
char * remove_vowels( char *s )
{
const char *vowels = "aeiou";
char *src = s, *dsn = s;
do
{
if ( *src == '\0' || strchr( vowels, *src ) == NULL )
{
if ( dsn != src ) *dsn = *src;
dsn;
}
} while ( *src );
return s;
}
int main( void )
{
char s[] = "white milk";
printf( "%s -> ", s );
puts( remove_vowels( s ) );
}
The program output is
white milk -> wht mlk
Your main function can look like
int main( void )
{
char message[30];
while ( fgets( message, sizeof( message ), stdin ) != NULL &&
message[0] != '\n' )
{
printf( "%s", remove_vowels( message ) );
}
}