【发布时间】:2021-09-20 14:59:33
【问题描述】:
我正在尝试将 char 转换为二进制。所以首先我使用了static_cast< int >(letter),然后我使用了cout<<format("The binary value is {:b}",integer_value);。
我在 Visual Studio 2019 中使用 C++20,这就是我使用格式的原因。但是,我使用了它,但它给出了错误的值。例如,我输入了k,它显示二进制值0b1101011,但这是错误的,我在互联网上检查了它,k 应该等于01101011。显示了我的完整代码。
#include <iostream>
#include <format>
using namespace std;
int main()
{
cout << "Enter a letter: " << endl;
char lett{};
cin >> lett;
switch (lett)
{
case 'A':
case 'a':
case 'i':
case 'I':
case 'o':
case 'O':
case 'u':
case 'U':
cout << "You entered a vowel \n";
break;
default:
cout << "The letter is not a vowel \n";
break;
}
if (islower(lett))
{
cout << "You entered a lower case letter \n";
}
else if (isupper(lett))
{
cout << "The letter is not lower case \n";
}
// conver letter to lowercase and binary value
int inti{(static_cast<int>(lett))};
cout << format("The lower case letter is {} and its binary value is 0b{:b} \n\n\n", static_cast<char>(tolower(lett)), inti);
return 0;
}
【问题讨论】:
-
01101011和1101011是同一个数字。如果你想要前导零,你可以使用像0b{:08b}这样的格式传递一个宽度。 -
有几件事可能会出错,例如输入,转换为不同的整数类型,或最后格式化和输出。缩小范围以找出其中哪些失败了。
标签: c++ visual-studio binary c++20