简体   繁体   English

C ++中的char和'0'比较未给出所需的结果

[英]char and '0' comparison in c++ not giving wanted results

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 我正在从文件中读取二进制值,并且必须进行比较,无论是1还是0,但是当我尝试比较时

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

The above code is not executing even when ch='0' 即使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? 它与ASCII编码有关系吗?

From a comment: The content of the file is 01101111111111111100000000 just like that. 注释:该文件的内容就是01101111111111111100000000 It's a .txt file 这是一个.txt文件

Your question leaves some space for interpretation. 您的问题留出了一些解释的空间。

You say that your file contains '1' and '0'. 您说您的文件包含“ 1”和“ 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 (ie: 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 ). 如果是,那么您想先按字节读取字节(即:逐个字符),然后在该字节上迭代应用一些掩码,以查看在字节中给定的位置处是一个还是零(这- 如何将char转换为二进制? -可能有帮助)。

Never use eof() as an alternative for checking whether the reading from the file was successful or not. 切勿使用eof()作为检查文件读取是否成功的替代方法。

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++;
}

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

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