Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change vowels in a string to a symbol?

Tags:

c

loops

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?

like image 240
adohertyd Avatar asked Dec 04 '25 18:12

adohertyd


1 Answers

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;
}
like image 84
MByD Avatar answered Dec 06 '25 08:12

MByD