Search code examples
carraysstringstdinrpn

Store contents of a file with both integers and characters in C


I have a text file input.txt whose contents are of the form:

12 3 /
2 3 -
3 4 *
1 2 4 + - 5 * 7 /

My end goal is to read each line of the file and evaluate the given RPN expression. I have written the following code snippet to read the contents of the file from stdin and store it in a character array:

char expression[1000][256];
int i = 0;
while (fgets(expression[i], 256, stdin)) 
{   
    expression[i][strcspn(expression[i],"\r\n")] = 0;
    i++;
}

Now, I have all the lines in the array. My issue here is that I want to store these such that there are no spaces and each number (with all digits) or character is in a separate index.

For example, here, expression[0][0] is 1 and expression[0][1] is 2. But, I want expression[0][0] to be 12 and expression[0][1] to be 3, etc.


Solution

  • Good work with your example so far! Thanks for posting a question that explains what you want, and making an attempt at solving it.

    The main problem you've got is that you're storing an array of array of chars, when you need an array of array of strings (remember a string is a char *).

    I've used the [strtok][1] method, which splits a string (using a NULL character) every time it hits one of the characters listed in its call. I then allocate memory, and copy the string into the array.

    I made up some example code (try it online) which does just this.

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    int main() {
        char* expression[1000][256];
        char buffer[256];
        int line = 0;
    
        while (fgets(buffer, 256, stdin)) {
            int word = 0;
            char* token = strtok(buffer, " \r\n");
            do {
                expression[line][word] = calloc(sizeof(char), strlen(token) + 1);
                strcpy(expression[line][word], token);
                word++;
            } while ((token = strtok(NULL, " \r\n")) != NULL);
            line++;;
        }
        printf("'%s', '%s', '%s'\n", expression[0][0], expression[0][1], expression[0][2]);
        return 0;
    }