Reputation: 81
#include <iostream>
#include <string>
#include <stdlib.h>
using namespace std;
int main()
{
string x;
cin>>x;
if(strcmp(&x.at(0), "M") == 0)
{
cout<<"midget ";
}
else if(strcmp(&x.at(0), "J") == 0)
{
cout<<"junior ";
}
else if(strcmp(&x.at(0), "S") == 0)
{
cout<<"senior ";
}
else
{
cout<<"invalid code";
}
if(strcmp(&x.at(1), "B") == 0)
{
cout<<"boys";
}
else
{
cout<<"girls";
}
return 0;
}
I've used the above code to compare MB which should return "midget boys" but it keeps falling to else and returns "invalid codeboys". Somehow the second condition works fine. My diagnostics tell me that at the first comparison it returns 66
. I guess that is the ASCII code for "M". But how do I solve my problem now?
Upvotes: 2
Views: 4083
Reputation: 1993
When interpreted as a C-style string &x.at(0)
is actually equivalent to x.c_str()
: both of these return a pointer to the first character in the string. Functions like strcmp
, which operate on C-style strings, will determine the string length by reading until the first null character.
Thus, in your example, your first test compares "MB" with "M".
Your test for the second character works of course, because the "B" is immediately followed by the null delimiter.
As others have already said, you can do what you need via a direct char
comparison: x.at(0) == 'M'
Upvotes: 2
Reputation: 2124
strcmp expects to compare two null-terminated strings. It will start comparing the first character of each string. If they are equal to each other, it continues with the following pairs until the characters differ or until a terminating null-character is reached.
You want to compare two chars. Try this:
if(x.at(0) == 'M')
...
Upvotes: 7