1

I am new at C programming. I have an input file and I want to skip first line of the input file and try to compose output file.My file contains some graph information. I want to get u,v,w values from input file instead of user enters.But I am getting no value for u,v,w.

printf("Enter (u v w):\n");
    for(i = 0; i < edges; ++i){
        scanf("%d%d%d", &u, &v, &w);
     }

I tried like this :

fgets(buffer, 1024, inputFile);       
        while( ( ch = fgetc(inputFile) ) != EOF )   
        {
         sscanf(buffer, "%d%d%d", &u, &v, &w);
          }
zeynep
  • 17
  • 1
  • 7
  • 1
    What does the data look like? – Taelsin Mar 29 '16 at 22:53
  • it contains just numbers like: 1 2 3 – zeynep Mar 29 '16 at 22:55
  • 2
    Your algorithm says: read a line. Then, while throwing away characters one at a time from the file, repeatedly scan the first (and only) line read for three `int` values? Not sure that was your intent, but I'm guessing not. – WhozCraig Mar 29 '16 at 22:58
  • No, to skip only first line is enough for me. Other lines contain graph information. – zeynep Mar 29 '16 at 22:59
  • 1
    Something tells me `while( ( ch = fgetc(inputFile) ) != EOF )` was supposed to be something like: `while( fgets(buffer, 1024, inputFile) )`, or something similar. That assuming your intent on scanning `buffer` repeatedly for 3 `int` values was to perform per-line processing and reading the first three (and only the first three) `int` values, ignoring the rest of each line of anything extraneous. – WhozCraig Mar 29 '16 at 23:01
  • duplicate. There is on liner solution described here http://stackoverflow.com/a/16108311 – dimm Mar 30 '16 at 01:01

1 Answers1

2

Maybe like this:

fscanf(inputFile, "%*[^\n]"); // Read and discard a line
while(fscanf(inputFile, "%d%d%d", &u, &v, &w) == 3 )   
{
    ...
}

Example code:

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    int u, v, w;
    FILE *fp;
    fp = fopen("data.txt", "r");
    if (!fp)
    {
        perror("fopen()");
        exit(EXIT_FAILURE);
    }
    fscanf(fp, "%*[^\n]");  // Read and discard a line
    while (fscanf(fp, "%d%d%d", &u, &v, &w) == 3)
    {
        printf("%d %d %d\n", u, v, w);
    }
    fclose(fp);
}

data.txt

1 2 3
4 5 6
7 8 9

output:

4 5 6
7 8 9
nalzok
  • 14,965
  • 21
  • 72
  • 139