0

I'm writing a C program that reads table data from a .txt file, applies changes to it and prints the modified table to a different .txt file. Part of the program is the function that prints and empty line before the line entered in the terminal after the irow argument. Here's how the program is compiled and run:

gcc -Wall -Wextra -Werror -o main main.c
./main irow [row]  <tab1.txt >tab2.txt

Part of the program that handles the input:

int insertRow(char*argv[], int row_number) {
    row_number = 0;
    for(int i = 0; argv[i]; i++) {
        if ( isdigit(argv[i][0]) && (strcmp(argv[i - 1], "irow") == 0))
            if((argv[i][0] - '0') > 0)
                row_number = argv[i][0] - '0';
    }
    return row_number;
}

Then the row_number is used in the main method to perform the changes on the table.

The code works and performs what it's supposed to, however I haven't yet come up with a better way of reading the [row] parameter from the argument vector. How can I read not only the first digit but the whole integer inside the string of that argument?

harvey
  • 5
  • 2

2 Answers2

1

To turn a string containing a number into an int:

row_number = atoi(argv[i]);

Also, you're not supposed to get row_number in the signature. You're not using its value, and any changes you make to row_number won't affect the calling function. You should instead define it inside the function:

int row_number = 0;
Camelid
  • 1,535
  • 8
  • 21
Shlomi Agiv
  • 1,183
  • 7
  • 17
1

Because the first executable statement of your function is to set row_number to 0, there is no need to have it as an argument. It ignores the passed in value and returns the final value.

Also, there are simpler ways to use argv than to index into it.

And, if you had arguments of:

23 irow 17

Your function won't handle that well. It would try to decode 23 instead of 17

It is simpler to have a "state" variable and look at only one argument at a time.

And, you can/should use atoi to get all the digits [vs. decoding only the first digit of the number string].

Here's a refactored version:

#include <string.h>
#include <stdlib.h>

int
insertRow(char **argv)
{
    char *cp;
    int match = 0;
    int row_number = 0;

    for (cp = *argv++;  cp != NULL;  cp = *argv++) {
        // we just saw "irow", so this is the number
        if (match) {
            row_number = atoi(cp);
            break;
        }

        // if current token is "irow", next token is the number
        match = (strcmp(cp,"irow") == 0);
    }

    return row_number;
}
Craig Estey
  • 30,627
  • 4
  • 24
  • 48