I need to change the vowels in a string to a $ using C. I know that I need to use a for loop and I'm pretty sure I'm on the right track but I can't get it to work.
Here is my code:
#include <stdio.h>
#include <string.h>
int main(void)
{
char input[50];
char i;
int j = 0;
printf("Please enter a sentence: ");
fgets(input, 50 , stdin);
for (j = 0; input[i] != '\0'; j++)
if (input[i]=='a'||input[i]=='e'||input[i]=='i'||input[i]=='o'||input[i]=='u')
{
input[i]= '$';
printf("Your new sentence is: %s", input);
}
return 0;
}
I know my error is not a big one but I just can't see it. This is homework so I don't want a solution as such just some advice so that I can actually learn from this.
Edit:
Thanks for that guys I got rid of 'j' and it now works however when I run the program it outputs a new line for every vowel it changes. How do I code it so that it only outputs the final line i.e. with all of the vowels changed?
You made a small mistake with the index:
for (j = 0; input[i] != '\0'; j++)
^ ^
should be
for (i = 0; input[i] != '\0'; i++)
Actually, you can omit j:
int main(void)
{
char input[50];
int i;
printf("Please enter a sentence: ");
fgets(input, 50 , stdin);
for (i = 0; input[i] != '\0'; i++)
{
if (input[i]=='a'||input[i]=='e'||input[i]=='i'||input[i]=='o'||input[i]=='u')
{
input[i]= '$';
}
}
printf("Your new sentence is: %s", input);
return 0;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With