equality on char type

I'm making a program that receives input from cout and uses cin to put a value in a char.


1
2
3
4
5
6
7
char name[20];

cout << "name? "; //types in name 'bob'
cin >> name;

if (name == "bob") //why doesn't this work?
//do stuff 
You can't do that with char arrays.
What you're looking for is a string:

1
2
3
4
5
6
string name;

cout << "name? ";
cin >> name;

if (name == "bob")
thanks
std::string has a overloaded operator==, so you can use it for comparison. You can't do the same with raw arrays.

slackPLUSPLUS wrote:
isn't that equivalent to a string? using the double quotes?

No. "bob" is a string literal, i.e. a constant, null-terminated char array. When you assign that to a char pointer, it will point to the first character of the string literal. That's all d is - a primitive pointer.

slackPLUSPLUS wrote:
which library do I need to use the 'string' type?

The header for std::string is called string.
oic....

so if I wanted to, I could of did
1
2
3
if ( name == 'b') // works because it is the first character of the char array

//do stuff 

How would I make a conversion from char type to string?
Last edited on
Not quite, you need to dereference the pointer first the get the char value it's pointing to:
if (*name == 'b')
But yeah, that would compare the first character.

slackPLUSPLUS wrote:
How would I make a conversion from char type to string?

std::string has a contructor that takes a const char*. So you can do the following:
1
2
const char* cstring="bob";
string realString=cstring;
Last edited on
That's not the proper usage for the results you want, since now "bill" or "b" or anything that starts with a b is a valid input. Use strings as suggested:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include <string>

using namespace std;

int main()
{    string name;
     cout << "Please input your name: ";
     getline(cin, name); // Use getline for inputting strings
     if (name == "bob")
     {   // do stuff
          }
     // Pause your program here
     return 0;}
try
 
if(strcmpi(name,"bob")==0)cout << "Is the same string!" << endl;
Last edited on
if(strcmpi(name,"bob")==0...

Eww, no. strcmpi is not even part of the C++ (or C) standard. strcmp is, but there is no place for that in a C++ program.
Also, don't confuse the terms "same" and "equal".
Topic archived. No new replies allowed.