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 comments.
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);
}
Comparing "magic" with 0 is undefined behaviour since it's not initialized yet (so it's basically just a chunk of memory):
Consider initializing variable before comparing:
In this function:
(I'm assuming that ERROR = -1, is that correct?) In your condition
getchar()will work 3 times, not 1 (since it callsgetchar()for putting inchevery check). Rewrite it to call only once for saving in variablech. Another problem occurs when first symbol will be whitespace, not digit. In this casevalwill remains0(sincewhileloop will be skipped), so returned value will also be '0'. To avoid this, you can check value ofvaland return ERROR, when it is not changed:UPD: We can also use this fact to simplify our function a lot:
And last but not least, remove extra '' before symbols (
\\n->\n,\>=->>=etc.) if they present in your code.Combining everything above results in something like this:
Result: