-4
string C; cin>>C; if (C=="add" ){ int a=add(A,B); cout<<a<<endl; 

I have here a simple condition where i am taking input "C" to ask the user to write which math operation they want to run. The user might input in capital letters or the first letter might be uppercase and the rest be lowercase. What should I do so that the program reads all the inputs weather uppercase or lowercase as the same?

0

1 Answer 1

1

Transform the user input into all lowercase or uppercase.

#include <algorithm> #include <cctype> #include <string> std::string toLowerCase(const std::string& str) { std::string lower(str); std::transform(lower.begin(), lower.end(), lower.begin(), ::tolower); return lower; } 
Sign up to request clarification or add additional context in comments.

4 Comments

@Evg -- if the value of EOF is -1 the code in that note introduces undefined behavior. For keyboard input it's a bad solution to a non-problem.
@PeteBecker Can you please elaborate on why the code in that note introduces UB? Because casting -1 to an unsigned integer is well defined in C++: it produces a value with all bits set. Thus, static_cast<unsigned char>(-1) is just 255 (assuming unsigned char is 8-bit, which is typically the case). And then, since 255 is "representable as unsigned char" (because we've just converted it by casting), I don't see UB here.
@heapunderrun -- sorry, got carried away. But if EOF is -1, casting it to unsigned char gives it a different meaning. And unless tolower maps 255 to a value between 0 and 127, the effect of casting the result of tolower(255) to char is implementation defined. So you really can't count on anything.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.