I write a program to read values from text file and treating them as a pixel values for demo.My task is to scan a value for pixel position, if the value is row value is greater than 2 or column value is greater than 1 the it will print "invalid pixel position\\n" then "to exit press \\"q\\" or to continue for next position press \\"c\\" . after this it will scan for input. Now the problem is if I enter invalid value , for example 3,5 it prints the printf() statement two time then it comes on scanf() function. here is my code:-
#include"stdio.h"
#include"stdafx.h"
#include"conio.h"
int r,c,check;
int main()
{
FILE *p;
char l[3],m[3],n[3],i,j,k,a;
p=fopen("s.txt","r+");
goto tab;
// int r,c,check;
tab:
{
while(1)
{
fseek(p,0,SEEK_SET);
printf("enter the position\n");
scanf("%d\n%d",&r,&c);
while((r>2)|(c>1))
{
printf("invalid pixel position\n");
printf("to exit press \"q\" or to continue for next position press \"c\":-\n");
scanf("%c",&check);
if(check=='c')
{
goto tab;
}
else if(check=='q')
{
return 0;
}
}
printf("you ask for pixel %c %c- ");printf("%2d%2d\n",r,c);
for(k=0;k<=r;k++)
{
for(i=0;i<=c;i++)
{
for(j=0;j<3;j++)
{
fread(&l[j],sizeof(a),1,p);
fread(&m[j],sizeof(a),1,p);
fread(&n[j],sizeof(a),1,p);
fread(&a,sizeof(a),1,p);
}
}
}
for(i=0;i<3;i++)
{
if(i==0)
{
printf(" red= %c%c%c",l[i],m[i],n[i]);
}
if(i==1)
{
printf(" green= %c%c%c",l[i],m[i],n[i]);
}
if(i==2)
{
printf(" blue= %c%c%c\n",l[i],m[i],n[i]);
}
}
}
}
fclose(p);
getch();
}
You have a very common error with your use of scanf
, namely that it leaves the newline in the input buffer and scanning for characters reads all characters including newline.
The two problematic lines are these:
scanf("%d\n%d",&r,&c);
...
scanf("%c",&check);
The first scanf
function, as I said above, leave the last newline in the input buffer for the second scanf
to read. This is very simple to fix, by adding a leading space in the second scanf
format code which instructs the function to skip leading whitespace:
scanf(" %c",&check);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.