简体   繁体   中英

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

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

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM