出于某种原因,布尔值返回 false
Bool value returning false for some reason
抱歉,如果这很明显,但我对 c++ 很陌生,提前谢谢
#include <iostream>
bool conduct_it_support(bool on_off_attempt) {
std::cout << "Have you tried turning it off and on again? (true / false)n";
std::cin >> on_off_attempt;
if(on_off_attempt == false) {
return false;
}
else {
return true;
}
return on_off_attempt;
}
int main() {
bool attempt;
conduct_it_support(attempt); {
std::cout << "so it was " << attempt << "?n";
}
}
我的意思是:"所以这是真的/假的?抱歉,如果这很明显,但我对 c++ 很陌生,提前谢谢
默认情况类会将bool
序列化为 0
或 1
。反序列化时,它们还将读取0
或1
。
若要使其打印字符串true
或false
,需要使用流修饰符std::boolalpha
来更改流的行为,以打印(或读取(布尔值的文本版本。
见下文:
#include <iostream>
#include <iomanip>
int main ()
{
bool a = false;
bool b = true;
std::cout << std::boolalpha << a << " : " << b << 'n';
std::cout << std::noboolalpha << a << " : " << b << 'n';
// If you want to read a bool as 0 or 1
bool check;
if (std::cin >> std::noboolalpha >> check) {
std::cout << "Read Worked: Got: " << check << "n";
}
else
{
std::cout << "Read Failedn";
}
// PS. If the above read failed.
// The next read will also fail as the stream is in a bad
// state. So make the above test work before using this code.
// If you want to read a bool as true or false
bool check;
if (std::cin >> std::boolalpha >> check) {
std::cout << "Read Worked: Got: " << check << "n";
}
else
{
std::cout << "Read Failedn";
}
}
这段代码工作正常:
bool conduct_it_support(bool init) {
bool on_off_attempt=init;
char selectVal[10] = "000000000";
std::cout << "Have you tried turning it off and on again? (true / false)n";
std::cin >> selectVal;
if(selectVal == "false") {
on_off_attempt=false;
}
else {
on_off_attempt=true;
}
return on_off_attempt;
}
int main()
{
bool attempt;
attempt = conduct_it_support(attempt); {
std::cout << "so it was " << attempt << "?n";
}
在此处尝试此代码。
相关文章:
- QueryWorkingSet总是返回false
- 当返回类型声明为 ListNode 时,我们是否可以返回 false<T>*
- 等于在 c++ 中返回 false
- strcmp 对于相等的字符序列返回 false
- C++ - 负数和正数之间的比较返回 false
- protobuf 的 ParseFromString 函数返回 false
- 递归函数始终返回 false
- 为什么 GetExitCodeThread() 在这里返回 FALSE?
- MFC 的 OnInit() 函数中的返回 true 和返回 false 有什么区别
- if 语句在条件为真时返回 false
- 为什么 std::isnan() 对于具有 NAN 值的双变量返回 false
- is_lock_free() 在升级到 MacPorts gcc 7.3 后返回 false
- 在 winapi 回调函数上返回 FALSE 时出现意外行为(循环被跳过?
- 如果数组中有重复的数字,如何返回'false'?
- std::is_array 当它应该返回 false 时返回 true
- 为什么pyarg_parsetuple总是返回false
- 删除为应该在哈希表中的记录返回 false 的函数
- Vulkan 和 glfwVulkanSupported() 总是返回 false
- tf2_ros::Buffer::canTransform() 为现有转换返回 False
- 出于某种原因,布尔值返回 false