0

i am having a binary value read from file and have to make comparison whether its a 1 or 0 but when i try to compare

char ch;
while(!in.eof()){
    in.get(ch);
    if(ch=='0') count0++;
}

The above code is not executing even when ch='0'

if(ch=='1') count1++;

that too is not giving me correct answer how these can be compared? it has to do something with the ascii coding or something?

From a comment: The content of the file is 01101111111111111100000000 just like that. It's a .txt file

tomsv
  • 7,207
  • 6
  • 55
  • 88
sara
  • 95
  • 5
  • 14

2 Answers2

0

Your question leaves some space for interpretation.

You say that your file contains '1' and '0'. All files contain ones and zeros. Computers contain nothing more than ones and zeros (joke!).

Since you say that you have a binary file, I assume that what you try to ask is how to read the contents of the file bit by bit. Is that what you are asking?

If not, then you already have answers in the comments. Discard the rest of this message.

If yes, you'd want to first read byte by byte (i.e.: char by char) as you are doing and then iteratively apply some masks upon the byte to see whether at the given position in the byte there is a one or a zero ( this - how to convert a char to binary? - might help ).

Community
  • 1
  • 1
CristiArg
  • 103
  • 2
  • 7
  • no the content of the file is 01101111111111111100000000 just like that it's a .txt file – sara Sep 26 '13 at 11:10
0

Never use eof() as an alternative for checking whether the reading from the file was successful or not.

It could look the following way:

std::ifstream in("test.txt", std::ifstream::in);
if (!in.is_open()) {
    std::cout << "Error opening file";
    return -1;
}

int count0 = 0,
    count1 = 0;
char ch;
while (in.get(ch)) {
    if (ch == '0')
        count0++;
    else if (ch == '1')
        count1++;
}
LihO
  • 41,190
  • 11
  • 99
  • 167