Jan 2, 2020 at 3:09pm UTC
For starters,
strcmp returns 0 if the words are the same. You're comparing against 1, which means they're different in a very particular way. The could be different and the number is -1. They could be different and the number is 17; it's implementation defined.
But even using strcmp here is not good. If you're going to write C++, then write C++.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
#include<iostream>
#include<string>
using namespace std;
int main()
{
string class_name;
cin>>class_name;
while (class_name != "Business" &&
class_name != "business" &&
class_name != "Economy" &&
class_name != "economy" &&
class_name != "Public" &&
class_name != "public" )
{
cout<<"Error!! Invalid Input(Plz Enter Business,Public,Economy Only)" ;
cout<<"\nRe-Enter Class:" ;
cin>>class_name;
}
}
Last edited on Jan 2, 2020 at 3:14pm UTC
Jan 2, 2020 at 3:14pm UTC
Why are you using C-strings instead of C++ strings? Comparison of C++ strings is much easier.
If you must use C-strings you probably should look up your documentation for strcmp(), it doesn't return 1 for a match.
You may also want to consider transforming the class_name to a single case, then you would only need to check for one option.
Jan 2, 2020 at 3:51pm UTC
and a general design thing: making a user type that much is 'unfriendly'. Put a menu on it and let them type a single digit or letter to select from the valid list. Its easier for both you and the user to do it this way: all they can mess up is a single letter, which can be covered in a default switch statement.
Jan 2, 2020 at 4:11pm UTC
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 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
#include <iostream>
#include <string>
#include <map>
#include <algorithm>
#include <cctype>
using std::string;
using std::map;
using std::cout;
using std::cin;
class SchoolClass {
public :
int num_credits;
};
std::string tolower(std::string str)
{
// https://stackoverflow.com/a/313990/8690169
std::transform(str.begin(), str.end(), str.begin(),
[](unsigned char c){ return std::tolower(c); });
return str;
}
int main()
{
map<string, SchoolClass> class_map = {
{ "business" , SchoolClass{1} },
{ "economy" , SchoolClass{4} },
{ "public" , SchoolClass{3} }
};
cout << "Enter Business, Public, or Economy: " ;
string class_name;
cin >> class_name;
class_name = tolower(class_name);
auto it = class_map.find(class_name);
while (it == class_map.end())
{
cout << "Error!! Invalid Input(Plz Enter Business,Public,Economy Only)\n" ;
cout << "Re-Enter Class: " ;
cin >> class_name;
class_name = tolower(class_name);
it = class_map.find(class_name);
}
cout << "Number of credits: " << it->second.num_credits << '\n' ;
}
Last edited on Jan 2, 2020 at 4:14pm UTC