Ele*_*ent 1 c++ binary visual-studio c++20
我正在尝试将 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;
}
Run Code Online (Sandbox Code Playgroud)
显示的输出在数字上是正确的 \xe2\x80\x93 它只是缺少一个前导零。0您可以通过指定字段宽度 (8) 并在说明符中添加 来强制添加前导零。
以下行(使用{:08b})将以所需的格式输出二进制值:
cout << format("The lower case letter is {} and its binary value is 0b{:08b} \\n\\n\\n", static_cast<char>(tolower(lett)), inti);\nRun Code Online (Sandbox Code Playgroud)\n有关格式说明符的更多详细信息可以在此 cppreference 页面上找到(具体来说,对于本例,是“填充和对齐”和“符号、# 和 0 ”部分)。
\n| 归档时间: |
|
| 查看次数: |
424 次 |
| 最近记录: |