// Allow the user to enter 'true' or 'false' for boolean values // This is case-sensitive, so True or TRUE will not work std::cin >> std::boolalpha; std::cin >> b;
std::cout << "You entered: " << b << '\n';
//上面的代码允许你输入true 或者 false //下面的代码会输出true 或者 false std::cout << std::boolalpha; bool b1 = 4 ; // copy initialization allows implicit conversion from int to bool std::cout << b1 << '\n';
bool b2 = 0 ; // copy initialization allows implicit conversion from int to bool std::cout << b2 << '\n'; }
intmain() { print( static_cast<int>(5.5) ); // explicitly convert double value 5.5 to an int
return0; }
1 2 3 4 5 6 7 8 9 10 11
#include<iostream>
intmain() { char ch{ 97 }; // 97 is ASCII code for 'a' std::cout << ch << " has value " << static_cast<int>(ch) << '\n'; // print value of variable ch as an int
return0; }
//a has value 97
要将无符号数转换为有符号数,还可以使用 static_cast 运算符:
1 2 3 4 5 6 7 8 9 10
#include<iostream>
intmain() { unsignedint u { 5 }; int s { static_cast<int>(u) }; // return value of variable u as an int
std::cout << s << '\n'; return0; }
std::int8_t 和 std::uint8_t 的行为可能类似于字符而不是整数
1 2 3 4 5 6 7 8 9 10 11 12
#include<cstdint> #include<iostream>
intmain() { std::int8_t myInt{65}; // initialize myInt with value 65 std::cout << myInt << '\n'; // you're probably expecting this to print 65