Toupper function doesn't work properly in 1d array (c)

76 Views Asked by At

I'm trying to uppercase the keywords in 1d array by using function toupper and additional array, but the code doesn't work properly

My code is:

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

int main () {
    char prog1[20], prog2[20];
    char ch1, ch2;
    int j = 0;
    printf ("Enter a prog:");
    gets(prog1);
    printf ("Enter keywords:");
    gets(prog2);
    char upper = toupper(ch2);
    while (prog1[j])
    {
        ch1 = prog1[j];
        ch2 = prog2[j];
        putchar(toupper(ch2));
        j++;
    }
    return 0;
}

The result is:

Enter a prog:aaa bbb ccc
Enter keywords:bbb
BBB`?

The goal is to receive result like this:

Enter a prog:aaa bbb ccc
Enter keywords:bbb
aaa BBB cccc

I would highly appreciate your help

1

There are 1 best solutions below

0
edFabbris On

You need to initialize the array, therefore cleaning them in the beginning:

char prog1[20] = {'\0'}, prog2[20] = {'\0'};

Then, you can do like this:

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>


int main () {
    char prog1[20] = {'\0'}, prog2[20] = {'\0'};
    char ch1, ch2;
    int i = 0, j = 0;
    printf ("Enter a prog:");
    gets(prog1);
    printf ("Enter keywords:");
    gets(prog2);
    
    while (prog1[i])
    {

        j = 0;
        while(prog2[j]){
            if(prog1[i] == prog2[j]){
               prog1[i] = toupper(prog2[j]); 
            }

            j++;
        }

        putchar(prog1[i]);    

        i++;
    }
    return 0;
}