-1

I'm trying to write a program that takes in user input from keyboard, stores it in a 2D array, and prints it in revers order. So, if a user typed in:

Line 1

Line 2

The output would be:

Line 2

Line 1

However, I'm stuck on a break condition in my if statement inside the first for loop. Even though I type in "STOP" the program still waits for input. I assume the problem might be due to strcmp function because when I print out the value returned from the function, I'm not getting zero even though my input was "STOP".

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

int main(){
    int i, words = 500, characters = 100, arraylen;
    char array[words][characters];

    arraylen = sizeof(array)/sizeof(array[0][0]);

    printf("Enter lines of words( type \"STOP\" to quit):\n");

    for(i = 0; i < arraylen; i++){
        fgets(array[i], 100, stdin);

        //printf("Value at index %d is %s", i, array[i]);
        //printf("Value of strcmp: %d\n", strcmp(array[i], "STOP"));

        if(strcmp(array[i], "STOP") == 0){
            //if(fgets(array[i], 500, stdin) == "STOP")
            break;
        }
    }

    printf("\n");

    for(i = arraylen - 1; i >= 0; i--){
        printf("%s", array[i]);
    }

    printf("\n");

    return 0;
}
Oka
  • 23,367
  • 6
  • 42
  • 53
Tom
  • 39
  • 1
  • 6

1 Answers1

3

The maximum length of array is really just the value of words.

You also need to need to keep track of how many entries you've added so that you do not run out of space, and so that you can know which position to start printing from, afterwards. As is, you are attempting to print from the very end of the array, from memory that may not have been initialized.

fgets places the newline character ('\n'), if read, in the buffer. You'll either need to remove it, or use strncmp to limit your comparison to the length of your sentinel string.

if (strncmp(buffer, "STOP", 4)) {
    /* .. */
}

fgets can also fail, returning NULL to signal this. You need to check its return value in some way, and act appropriately.

An example program:

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

#define MAX_LEN 500
#define STR_LEN 100

int main(void) {
    char strings[MAX_LEN][STR_LEN];
    size_t i = 0;

    printf("Enter lines of words( type \"STOP\" to quit):\n");

    while (i < MAX_LEN && fgets(strings[i], STR_LEN, stdin)) {
        strings[i][strcspn(strings[i], "\n")] = '\0';

        if (strcmp(strings[i], "STOP") == 0)
            break;

        i++;
    }


    while (i--)
        printf("%s\n", strings[i]);
}
Oka
  • 23,367
  • 6
  • 42
  • 53
  • Thank you for taking the time to help me and for providing the example. My issue has been resolved. – Tom Jul 25 '21 at 00:20
  • @Tom Please do consider [accepting the answer if it best solves your problem.](https://stackoverflow.com/help/someone-answers) – Oka Jul 25 '21 at 00:34