//Modify the previous program such that only the users Alice and Bob are greeted with their names.
#include <iostream>
#include <string>
usingnamespace std;
int main()
{
string x;
cout<<"Hello! Please enter your name.\n\n";
cin>>x;
if (x=="Alice" or x=="Bob")
{
cout<<"Hello there, "<<x;
}
else
{
cout<<"sorry don't know you haha";
}
system("pause");
return 0;
}
The original code works fine but requires the user to input the name with that exact capitalization. "bob", "BOB" or "bOb" will give the "sorry don't know you" response. To make the comparison case-insensitive you could loop through the string and turn every character into lower case using std::tolower, and then compare the string to the lower case "bob".
1 2 3 4 5 6 7 8 9 10 11 12
void convertToLowerCase(std::string& str)
{
for (char& c : str)
{
c = std::tolower(c);
}
}
// in main
convertToLowerCase(x);
if (x == "alice" || x == "bob")
{
Another way is to write a comparison function that loops through both strings and call std::tolower on each pair of character before comparing them.
#include <iostream>
#include <string>
usingnamespace std;
int main()
{
string x;
char y = ' ';
cout<<"Hello! Please enter your name.\n\n";
cin>>x;
if (x=="Alice" or x=="Bob")
{
cout<<"Hello there, "<<x << '\n';
}
else
{
cout<<"sorry don't know you haha\n";
}
cout<<"Hello! Please enter your first initial.\n\n";
cin >> y;
// NOT CASE SENSITIVE - ONE WAY THE HARD WAY
if (y == 'A' or y == 'a')
cout<<"Hello there, "<< y << '\n';
else
cout<<"sorry don't know you haha\n";
// NOT CASE SENSITIVE - BETTER WAY
if(tolower(y) == 'a')
cout<<"Hello there, "<< y << '\n';
else
cout<<"sorry don't know you haha\n";
system("pause");
return 0;
}