-
strcmp with spaces
HI im trying to make a program where a user has to enter the department and the program will compare the department entered to redirect to its proper function.sadly some department have spaces in them which seems strcmp cant handle is there any other way? Here is a part of my code:
Code:
void database::eng(){
system("cls");
cout<<"______COLLEGE OF ENGINEERING______\n";
cout<<"__________________________________\n";
cout<<"which department?\n(case sensitive)\n";
cout<<"Civil Engineering\n";char ce[]="Civil Engineering\0";
cout<<"ECE and CpE\n"; char cp[]="ECE and CpE\n";
cout<<"[Ba]ck\n";char b[]="Ba";
cout<<"Choice: ";char input[20];
cin>>input;
if(strcmp(ce,input)==0){dep=ce;data.add();}
if(strcmp(cp,input)==0){dep=cp;data.add();}
if(strcmp(b,input)==0){data.college();}
else { cout<<"Invalid choice!\nPress enter and re-enter choice";
getch(); data.eng();}
}
thank you for helping
-
It's not the strcmp with the issue, it's that cin >> var uses space as a separator.
To read a string containing spaces, use getline().
Also, you should really consider using std::string instead of char arrays.
This gets you two very important things (at least)
- total protection from buffer overruns (imagine someone typing 100 chars into your array of 20 - this is not good).
- the ability to use == to compare strings (and not a function like strcmp)
-
Code:
char ce[]="Civil Engineering\0";
...
char cp[]="ECE and CpE\n";
For the first, the \0 is not necessary.
For the second, the \n is definitely not what you want in there.
...that said, I echo what Salem said about using std::string.