出于某种原因,布尔值返回 false

Bool value returning false for some reason

本文关键字:返回 false 布尔值 某种原因      更新时间:2023-10-16

抱歉,如果这很明显,但我对 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序列化为 01 。反序列化时,它们还将读取01

若要使其打印字符串truefalse,需要使用流修饰符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";
    }

在此处尝试此代码。