-
sscanf - tricky func.
Hi,
I`m trying to read the first out of two collums.
Im using the sscanf function, and get one surprise after the other.
Why is the following code printing everything twice?
Code:
FILE *Koord;
Koordinaten=fopen("hpgl.txt","r"); //reads from hpgl.txt
while(i<10&&fgets(buff,sizeof(buff),Koord)!=NULL) //do10x
{
if (sscanf(&buff[2],"%d%d",&x[i],&y[i])==2) //begin buff3 and take only 2int
{
//cout<<"i="<<i<<" x="<<x[i]<<" y="<<y[i]<<"\n";
printf("i=%d x=%d y=5d\n",i,x[i],y[i]);
i++;
}
}
getch();
}
The textfile looks like this:
pd2 1
pd6 5
........
And the output of my prog.:
i=0 x=2 y=1
i=1 x=2 y=1
i=2 x=6 y=5
...... it does everyting correct, but twice!?
Now another problem:
Here is what I want do do:
I have 2 colums of hexnumbers, and I only want to take the first one and read its byte value.
FDAC FF
24 F7
..........
Heres my code:
Code:
FILE *HexCode;
HexCode = fopen("hex.txt","r"); //reads from textfile
/*----- take the first hex goe to next line ------*/
for(i=0;i<5;i++)
{
fgets(buff,sizeof(buff),HexCode);
if (sscanf(&buff[0], "%x", &x[i])==1);
{
printf(" %x\n",x[i]);
}
}
getch(); //wait
}
What it does:
it reads everything, not only the first colum:
like:
FDAC
FF
24
F7
Can anyone help me?
-
How did you declare buff ?
Or for that matter, your arrays.
Snippets of where you think the problem is are not always that informative. Small complete programs which demonstrate a problem (which we can try) are so much better.
> if (sscanf(&buff[0], "%x", &x[i])==1);
You really don't want the ; at the end of this line
-
Here´s the complete code:
It does everything twice.
Code:
#include<iostream.h>
#include<stdio.h>
#include<conio.h>
#include<ctype.h>
//-------------------------------------------------
void main()
{
int i,j;
int x[10], y[10];
char buff[6];
FILE *Koordinaten;
Koordinaten=fopen("hpgl.txt","r"); //reads from hpgl.txt
clrscr();
//------------------------------------------------------------------------------
while(i<4&&fgets(buff,sizeof(buff),Koordinaten)!=NULL)//do10x orempty buff
{
if (sscanf(&buff[2],"%d%d",&x[i],&y[i])==2) //begin buff3 and nimm nur 2int
{
//cout<<"i="<<i<<" x="<<x[i]<<" y="<<y[i]<<"\n";
printf("i=%d x=%d y=5d\n",i,x[i],y[i]);
i++;
}
}
getch();
}
Here it takes everything, not only the first nr.:
Code:
/**********************
//TestBuff10 *
/**********************/
#include<windows.h>
#include<iostream.h>
#include<conio.h>
#include<stdio.h>
int main()
{
char buff[6] ;
int i;
int x[10];
FILE *HexCode;
HexCode = fopen("hex.txt","r"); //reads hex.txt
clrscr();
while (i<10 && fgets(buff,sizeof(buff),HexCode)!= NULL)
{
if (sscanf(&buff[0], "%x", &x[i])==1)
{
printf(" %x\n",x[i]); i++;
}
}
getch();
}