Link to home
Start Free TrialLog in
Avatar of gvijay1
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.
ASKER CERTIFIED SOLUTION
Avatar of chensu
chensu
Flag of Canada image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of nietod
nietod

Right,b ut the other way around is more efficient.  Just use the [] operator to obtain a single character from the string.  i.e somestring[x] returns the character at position x (with 0 being the first position).  So

if (str[0] == 'a')
>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.
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")  

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.
Avatar of gvijay1

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.  
Have you debugged it? What is the value of str after you input 'a'?
Avatar of gvijay1

ASKER

Oh I am sorry. There was another part of the program that was giving the error. This actually works.

Thanks!!