In a C++ interactive console program evaluating user commands, how is string equality...
Accenture technical mcq question, verified with a worked answer. Free to practise - no sign-up.
In a C++ interactive console program evaluating user commands, how is string equality tested against keyword exit?
Show answer & explanation
In C++, std::string objects support the == operator for direct equality comparison, allowing you to write if (userInput == "exit") to test if the input matches the keyword. When this condition is true, a break statement exits the loop, terminating program execution. Options B and C describe runtime errors that don't occur with proper string handling, and Option D is incorrect because strcmp is a C-style function unnecessary for std::string objects which overload the == operator.
Step-by-step Derivation:
Typical C++ console program flow: (1) Create std::string variable to store user input; (2) Use std::cin >> userInput or std::getline(std::cin, userInput) to read input; (3) Test equality with if (userInput == "exit") using the overloaded == operator; (4) Execute break; to exit the loop when condition is true. Example: std::string cmd; while(true) { std::cin >> cmd; if(cmd == "exit") break; /* process cmd */ }. This is the standard, safe pattern—no stack overflow, no crashes on whitespace (unless improperly handled elsewhere), and no need for C-style strcmp.