0

I'm making an "acronym maker" where a string is inputted and ran through with a loop to find capitalized letters and move the data into a separate "acronym" string. when I run this I get asked for string input on the acronym but fgets() does not run and the acronym printf prints something completely random such as "Acronym of " " is " ASXXXFFP". it seems the amount of rows in the string works completely fine as I will get this output as many times as rows declared. I also get asked for input if the R value is more than one, but never on the first row stringA[0]. In my head, this seemed like reasonable code.

#include <stdio.h>
#include <string.h>

int main() {

// declaring R as the variable for rows of array
    int R;

    printf("Enter the number of acronyms to add to the database: ");
    scanf("%d", &R);

    char stringA[R][50];
    char stringB[R][7];

// starting for loop to run this code for each row of the string arrays
    for(int i=0; i<R; i++){

// declaring b for use when scribing values in string[i] columns
        int b = 0;

// asking for input on stringA[i]
        printf("\nEnter the string to convert into an acronym: ");
        fgets(stringA[i], 50, stdin);

// after the input, running a loop for each character or 'column' in the current focused row
        for(int j=0; j<50; j++){

// if the character is capitalized, the ascii values should pick it up in this if statement
            if(stringA[i][j] >= 'A' && stringA[i][j] <= 'Z'){

//scribing the capitalized single character into a spot in the stringB for acronyms, incrementing b
                stringB[i][b] = stringA[i][j];
                b++;

            }

        }
// trying to print statement
        printf("Acronym of %50s is %7s", stringA[i], stringB[i]);
    }

}

i tried changing fgets to scanf, i tried using intermediary strings and using strcpy, i am stuck.I have no real immediate errors or warnings in the compiler. I don't see where to go from here honestly.

  • 1
    You're never adding a null terminator to `stringB[i]`. And if there are more than 6 capital letters in `stringA[i]`, you'll overflow the size of `stringB[i]`. – Barmar Oct 26 '22 at 20:59
  • FYI, you can use `if(isupper(stringA[i][j]))` – Barmar Oct 26 '22 at 21:00
  • 1
    @Kai Young The first call of fgets reads an empty string.:) – Vlad from Moscow Oct 26 '22 at 21:00
  • `fgets()` will null terminate the buffer (guaranteed). The inner `for()` loop should halt when it has reached the end of the string, not the end of the 50 byte buffer... – Fe2O3 Oct 26 '22 at 21:03
  • @Barmar You mean `if(isupper((unsigned char)stringA[i][j]))`, of course... Had a bit of a tussle with a _stickler for tiny details_ recently... `:-)` All good `:-)` – Fe2O3 Oct 26 '22 at 21:15
  • One more thing... Since they aren't used again, there's no point in the complexity of 2x2D arrays... A 1D array for input, and one for output would suffice. – Fe2O3 Oct 26 '22 at 21:18

0 Answers0