gvijay1
asked on
Strings to characters
I have used STL in C++ to read an input line as a string. Now, I need to make a comparison of this input and a character..say a. These are of incompatible types so this is not possible. How can I convert the string to a charcter to make a comparison or vice versa.
Also, I cannot read the fitst line as character due to other strings that follow. So reading the input as a character is not an option.
Also, I cannot read the fitst line as character due to other strings that follow. So reading the input as a character is not an option.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
>if (str[0] == 'a')
Yeah, I though of that. But what if str is "abc"? I think gvijay1 wants to determine if it is a single character.
Yeah, I though of that. But what if str is "abc"? I think gvijay1 wants to determine if it is a single character.
Oh I see. you were thinking he/she wants to check if its ONLY 1 character, then you could do
if (str == "a"')
or
if (str.length() == 1 && str[0] == 'a')
there are lots of options.
if (str == "a"')
or
if (str.length() == 1 && str[0] == 'a')
there are lots of options.
>if (str == "a")
I think the character is not a constant. That's why I use pch or strch to form a string given a character.
>if (str.length() == 1 && str[0] == 'a')
This will do.
I think the character is not a constant. That's why I use pch or strch to form a string given a character.
>if (str.length() == 1 && str[0] == 'a')
This will do.
ASKER
Dear Experts,
I have tried out your suggestion of
if (str == "a") and also
(str[0] == 'a')
but it is not able to male the comparison between the character a and my string input of a. Do you have any suggestions. The program compiles but cannot make the correct comparison.
I have tried out your suggestion of
if (str == "a") and also
(str[0] == 'a')
but it is not able to male the comparison between the character a and my string input of a. Do you have any suggestions. The program compiles but cannot make the correct comparison.
Have you debugged it? What is the value of str after you input 'a'?
ASKER
Oh I am sorry. There was another part of the program that was giving the error. This actually works.
Thanks!!
Thanks!!
if (str[0] == 'a')