0

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

Lvrnnk
  • 39
  • 5
  • 1
    Can you say what is the value of `ch2` in the first call of `toupper`? – Bob__ Dec 28 '22 at 00:06
  • ch2 is a keyword – Lvrnnk Dec 28 '22 at 00:07
  • 3
    Also, [don't use `gets`](https://stackoverflow.com/questions/1694036/why-is-the-gets-function-so-dangerous-that-it-should-not-be-used). – Bob__ Dec 28 '22 at 00:09
  • you are running off the end of prog2 – pm100 Dec 28 '22 at 00:10
  • 2
    @Lvrnnk _"ch2 is a keyword"_ - It most certainly is not. It's also unintialized when you do `char upper = toupper(ch2);` and you never use `upper` so what's the point with that? – Ted Lyngmo Dec 28 '22 at 00:14
  • 1
    You are iterating over the array `prog1` ("the program"), but you are printing characters from `prog2` ("the keywords"). As `prog2` is shorter, you are 1) printing the letters from `prog2` as uppercase (`BBB`), then 2) undefined behavior. This has nothing to do with `toupper()`, your program logic is broken. The many artifacts and unused variables show that you ventured into trial & error, which is never a good idea with C. You will need a rewrite with a clear logic. – DevSolar Dec 28 '22 at 00:16
  • 1
    Is the goal to "uppercase" the words in the *first* array (of chars) that are also present in the *second* array and to print out the transformed *first* array? That's what I'd assume from the example result, but that's not what your program is trying to do. – Bob__ Dec 28 '22 at 00:16

1 Answers1

0

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;
}
edFabbris
  • 1
  • 1