布尔值由于某种原因返回false

时间:2019-03-24 19:26:02

标签: c++

很抱歉,如果这很明显,但是我对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 ++还是很陌生,请提前感谢

2 个答案:

答案 0 :(得分:1)

默认情况下,流类将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 Failed\n";
  }

  // 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 Failed\n";
  }

}

答案 1 :(得分:-4)

此代码可以正常工作:

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";
    }

尝试使用此代码here