Search code examples
c++filecharunsigned

I/O Fail of unsigned char typed variable


I have a file named input.in. I need to read the number and store it in an unsigned char typed variable. I read in the number and print the content of the variable on the screen and I can see it's true(prints 1). However, the if statement fails. It prints False to the stdout. Why does this happen? How can I store this number into an unsigned char variable?

The input.in file:

asus@ubuntu:~/Desktop$ cat input.in 
1

I work on Ubuntu. sizeof(unsigned char)=1

#include <fstream>
#include <iostream>

using namespace std;

int main(){

    unsigned char ucbuffer;

    fstream in;

    in.open("input.in",ios::binary | ios::in);

    in.read((char*)&ucbuffer,1);

    cout << ucbuffer << endl;
    if (ucbuffer==1) cout << "True" << endl;
    else cout << "False" << endl;

        return 0;
}

Solution

  • if (ucbuffer==1) is false. The value is '1', not 1. The numerical value of '1' is 49.