Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using fscanf() to skip a string

Tags:

c

The input file is such that it has a string followed by an integer on first line and from second line it has a string followed by 2 integers. My below code works well but is there a way to skip the string ? I am just scanning it with some character array char sink[30]. Actually I don't need this value how can I use fscanf() to skip this string and just read integers.

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

int main()
{
    int v,i=0,f=1;
    static int *p,*q;
    FILE *fp;
    char sink[30];
    fp = fopen("some.txt","r");

    while(!feof(fp))
    {   
        if(f)
        {   
            fscanf(fp,"%s %d",sink,&v);
            p = (int *)malloc(sizeof(int)*v);
            q = (int *)malloc(sizeof(int)*v);
            f=0;
        }   
        else
        {   
            fscanf(fp,"%s %d %d",sink,&p[i],&q[i]);
            i++;
        }   
    }   

    fclose(fp);

    printf("The input vertices are\n");
    for(i=0;i<v;i++)
        printf("%d %d\n",p[i],q[i]);
    return 0;
}
like image 468
Gopi Avatar asked Nov 09 '25 04:11

Gopi


1 Answers

For discarding data in scanf you use an asterisk in between the format specifier such as %*s , %*c etc. This is the same for fscanf . Simply add an asterisk to scan and discard the string:

fscanf(fp,"%*s %d",&v);

This will scan a string from the file,discard it and will then scan and assign an integer to v. You can do the same for your second fscanf:

fscanf(fp,"%*s %d %d",&p[i],&q[i]);
like image 159
Spikatrix Avatar answered Nov 11 '25 05:11

Spikatrix



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!