• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 278
  • Last Modified:

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.
0
gvijay1
Asked:
gvijay1
  • 4
  • 2
  • 2
1 Solution
 
chensuCommented:
string str;

//...

char ch = 'a';
char pch[2] = { ch, '\0' };

if (str.compare(pch) == 0)
    //...
else
    //...


or


string str;

//...

char ch = 'a';
string strch = ch;

if (str.compare(strch) == 0)
    //...
else
    //...
0
 
nietodCommented:
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')
0
 
chensuCommented:
>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.
0
The new generation of project management tools

With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

 
nietodCommented:
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.
0
 
chensuCommented:
>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.
0
 
gvijay1Author Commented:
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.  
0
 
chensuCommented:
Have you debugged it? What is the value of str after you input 'a'?
0
 
gvijay1Author Commented:
Oh I am sorry. There was another part of the program that was giving the error. This actually works.

Thanks!!
0

Featured Post

Upgrade your Question Security!

Your question, your audience. Choose who sees your identity—and your question—with question security.

  • 4
  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now