Ad

Comparing The First And Third Character Of A String

- 1 answer

I have a .txt file that contains data in this format:

AxCs: 0.9467,
FyHd: 0.9489,
AzCf: 0.78973,
DhBh: 0.8874,
JyLt: 0.64351,
AxCb: 0.8743,

and so on...

I have a C program which receives, as input, a substring (e.g "Ax") and returns all the rows containing that substring (e.g "AxCs: 0.9467", "AxCb: 0.8743") and the average of their numerical values.

More exactly:
The program receives (from terminal) 3 parameters:

  1. The programname.exe
  2. The filetoread.txt
  3. The substring

And it prints:

  1. The passed substring
  2. The number of rows that matches the substring
  3. The average of all the numerical values of matched rows

The thing I want to change in the program is the following:
When I pass the two characters I want to have a match if the first and the third characters of each row in the .txt are the same of the passed ones. (e.g if I pass "AC", AxCs: 0.9467 and AxCb: 0.8743 should be matches).

This is the code:

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

#define MAXC 1024

int main (int argc, char **argv) {

    char buf[MAXC] = "", *str = NULL;   /* buffer for line and ptr to search str */
    size_t n = 0, len = 0;              /* counter and search string length */
    double sum = 0;                     /* sum of matching lines */
    FILE *fp = NULL;                    /* file pointer */
    char tmpstr[8];

    if (argc < 3) { /* validate 2 arguments given - filename, search_string */ 
        fprintf (stderr, "error: insufficient number of arguments\n"
                "usage: %s filename search_string\n", argv[0]);
        return 1;
    }

    if (!(fp = fopen (argv[1], "r"))) { /* open/validate file open for reading */
        perror ("fopen-filename");
        return 1;
    }
    str = argv[2];                      /* set pointer to search string */
    len = strlen (str);                 /* get length of search string */

    prefix2char = argv[2];
    len = strlen(prefix2char);    

    while (fgets (buf, MAXC, fp)) {             /* read each line into buf */

        memcpy(tmpstr, buf, 4);
        tmpstr[4] = 0;

        if (strstr(tmpstr, prefix2char)) { /* HERE IS THE PROBLEM: I should check the first and the third char */
            double tmp;

            if (sscanf (buf, "%*1023[^:]: %lf", &tmp) == 1) {
                sum += tmp;
                n++;
            }
        }
    }

    if (n)  /* if values found, output average */
        printf ("prefix '%s' avg: %.4f\n", str, sum / n);
    else    /* output not found */
        printf ("prefix '%s' -- not found in file.\n", str);
}

Can someone help me?

Ad

Answer

Simply compare the current line first character with the first character of the substring and the 3rd character of the current line with the 2nd of the substring. Like so:

if (tmpstr[0] == prefix2char[0] && tmpstr[2] == prefix2char[1])
Ad
source: stackoverflow.com
Ad