【问题标题】:Read header of PPM file only using getchar()Read header of PPM file only using getchar()
【发布时间】:2022-12-01 18:52:37
【问题描述】:

I need to read a PPM file but I'm limited to only using getchar() but I'm running into trouble ignoring whitespaces.

I'm using num=num*10+(ch-48); to read the height and width but don't know how to read them all at once while ignoring spaces and '\n' or cmets.

I use this to read the magic number:


int magic;
while(magic==0){
if (getchar()=='P')     //MAGIC NUMBER
magic=getchar()-48;
}
printf("%d\\n",magic);

i used this function to read the height and width which works only when the data in the header is seperated only by '\n'


int getinteger(int base)
{ char ch;
int val = 0;
while ((ch = getchar()) != '\\n' && (ch = getchar()) != '\\t' && (ch = getchar()) != ' ')
if (ch \>= '0' && ch \<= '0'+base-1)
val = base\*val + (ch-'0');
else
return ERROR;
return val;
}

this is the part in main()

height=getinteger(10);
    while(height==-1){
        height=getinteger(10);
    }

【问题讨论】:

    标签: c function getchar ppm


    【解决方案1】:

    Something like this?

    int getinteger(int base) {
        char ch = getchar();
        if (ch == EOF || ch == '
    ' || ch == '	' || ch == ' ')
            return getinteger(base); // continue, skip symbols
    
        if (ch < '0' || ch > '0' + base - 1)
            return ERROR;
    
        int val = 0;
        do {
            val = base * val + (ch - '0');
            ch = getchar();
        } while (ch >= '0' && ch <= '0' + base - 1);
        return val;
    }
    
    int main() {
        // dunno what's before
        int magic = 0;
        while (magic == 0) {
            if (getchar() == 'P') // MAGIC NUMBER
                magic = getchar() - '0';
        }
        printf("magic = %d
    ", magic);
        int height = getinteger(10);
        int width = getinteger(10);
        printf("height = %d, width = %d
    ", height, width);
        // dunno what's after
    }
    

    Result:

    $ echo "   
      P3   34  	  56" | ./a.out
    
    magic = 3
    height = 34, width = 56
    

    【讨论】:

    • Welcome to SO. Please be aware that code-only answers are considered to be of low quality. To improve, you can edit and add an explanation what you changed and why it was wrong.
    猜你喜欢
    • 2022-12-02
    • 2022-12-02
    • 1970-01-01
    • 2013-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多