简体   繁体   English

从文本文件中获取demo的像素值

[英]fetching pixel values for demo from text file

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:- 我编写了一个程序来读取文本文件中的值并将它们视为demo的像素值。我的任务是扫描像素位置的值,如果值是行值大于2或列值大于1它将打印“无效像素位置\\ n”然后“退出按”\\“q \\”或继续下一个位置按\\“c \\” 。之后它将扫描输入。现在问题是如果我输入无效值,例如3,5它打印printf()语句两次然后它出现在scanf()函数。这是我的代码: -

 #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. 使用scanf有一个非常常见的错误,即它将换行符留在输入缓冲区中,扫描字符会读取所有字符,包括换行符。

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. 如上所述,第一个scanf函数将最后一个换行符留在输入缓冲区中,以便读取第二个scanf 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格式代码中添加一个前导空格来指示函数跳过前导空格,这很容易修复:

scanf(" %c",&check);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM