unsigned char 类型变量的 I/O 失败

发布于 2024-12-19 02:10:03 字数 693 浏览 4 评论 0原文

我有一个名为 input.in 的文件。我需要读取该数字并将其存储在无符号字符类型变量中。我读入数字并在屏幕上打印变量的内容,我可以看到它是 true(打印 1)。但是,if 语句失败。它将 False 打印到标准输出。为什么会出现这种情况?如何将此数字存储到 unsigned char 变量中?

input.in 文件:

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

我在 Ubuntu 上工作。 sizeof(无符号字符)=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;
}

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

谜兔 2024-12-26 02:10:03

if (ucbuffer==1) 为 false。该值为 '1',而不是 1'1'的数值是49。

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文