0

I'm trying to read a txt file, get some information and put it in variables, but I'm not succeeding, because each line of my txt file starts with a character, and I need to skip that character.

Input file:

T1, 3, 0
T2, 3, 1
T3, 2, 2

I need to ignore the T and just take the numbers. I've tried using %*c in fscanf, but it didn't work.

int initialize()
{
    int n, n1, n2, n3, i = 0;
    FILE *fp;
    fp = fopen("input.txt", "r");
    if (fp == NULL)
    {
        printf("Error locating the file. Please try again!\n");
        exit(1);
    }
    while (fscanf(fp, "%d, %d, %d", &n1, &n2, &n3) != EOF)
    {

        p[i] = n1;

        if (p[i] > MAX)
        {
            printf("Woah! I am not a super computer. Please input upto 100 processes :)\n");
            exit(1);
        }

        b[i] = n2;

        a[i] = n3;
        i++;
    }
    fclose(fp);
    return i;
}

I apologize about my English, I'm from Brazil.

Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
  • 4
    `while (fscanf(fp, "T%d,%d,%d", &n1, &n2, &n3) == 3)` – pmg Jun 02 '22 at 08:00
  • 3
    Even better, `fgets()` first, then `sscanf()` (or write your own parser)... for a **much** better way of dealing with validation and/or errors. – pmg Jun 02 '22 at 08:05
  • 1
    The `%*c` in `fscanf` didn't work to skip the T because `%c` does not filter whitespace and was reading the previous newline. It would have needed a space, as `" %*c"` to ignore the newline. – Weather Vane Jun 02 '22 at 08:47

1 Answers1

0

You're overcomplicating things.

You want to read a T, so simply add a T to the format string:

while (fscanf(fp, "T%d, %d, %d", &n1, &n2, &n3) != EOF)

But this is not a good error check. You should change != EOF to == 3. Read the documentation about the return value.

A better approach is to use fgets for input and sscanf to parse the input. See this question for more reading: What can I use for input conversion instead of scanf?

klutt
  • 30,332
  • 17
  • 55
  • 95