Compiler Error

I'm trying to write a code in which the user gives an input and if the input is "T", "F", "true" or "false" they will get a boolean reflecting that. If they type in something other than the mentioned inputs they will get an error code and the boolean will default to false. But I'm having trouble compiling it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class UserInputHandler {
public: 
  bool GetBoolean() {
    std::string str;
    bool test;
    const std::string invalid_bool_("Failure: Must input 'T', 'F', 'true', or 'false'. Case sensetive.");
    std::getline(std::cin, str);
    if (str = "T") {
      test = true;
    } else if ( str = "F") {
      test = false;
    } else if (str = "true") {
      test = true;
    } else if (str = "false") {
      test = false;
    } else {
      std::cout << invalid_bool_ << endl;
      test = false;
    }
    std::cout << "Boolean: " << test << endl;    
    return test;
  }
};

int main() {
 UserInputHandler handler;
 handler.GetBoolean();
}


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
$ make
/usr/bin/g++ -Wall -Wextra -g test.cpp  -o test
test.cpp: In member function ‘bool UserInputHandler::GetBoolean()’:
test.cpp:26:18: error: could not convert ‘str.std::basic_string<_CharT, _Traits, _Alloc>::operator=<char, std::char_traits<char>, std::allocator<char> >(((const char*)"T"))’ from ‘std::basic_string<char>’ to ‘boolif (str = "T") {
                  ^
test.cpp:28:26: error: could not convert ‘str.std::basic_string<_CharT, _Traits, _Alloc>::operator=<char, std::char_traits<char>, std::allocator<char> >(((const char*)"F"))’ from ‘std::basic_string<char>’ to ‘bool’
     } else if ( str = "F") {
                          ^
test.cpp:30:28: error: could not convert ‘str.std::basic_string<_CharT, _Traits, _Alloc>::operator=<char, std::char_traits<char>, std::allocator<char> >(((const char*)"true"))’ from ‘std::basic_string<char>’ to ‘bool’
     } else if (str = "true") {
                            ^
test.cpp:32:29: error: could not convert ‘str.std::basic_string<_CharT, _Traits, _Alloc>::operator=<char, std::char_traits<char>, std::allocator<char> >(((const char*)"false"))’ from ‘std::basic_string<char>’ to ‘bool’
     } else if (str = "false") {
                             ^
makefile:10: recipe for target 'test' failed
make: *** [test] Error 1


Can someone give me advice on fixing this?
Your if statements are formatted incorrectly. For this you would use the double =='s to see
1
2
if (str == "T") {
test = true;


Then the output is either 1 for True or 0 for False, when I tested it. Which is the correct output, but I'm not sure if you're going for the output as "True" and "False."If so, there are easy implementations for this. You may also want to prompt for user input with a simple cout statement, just in case this is for an assignment.
Last edited on
Topic archived. No new replies allowed.