• 0

c++ Char comparing


Question

I have a:

char* buffer = new char[2048]; //this is its initialization, its value is set later.

How can I compare the char* to a string? like so...

if(buffer == 'exit'){ //Will not work
}
Link to comment
Share on other sites

3 answers to this question

Recommended Posts

  • 0

I have a:

char* buffer = new char[2048]; //this is its initialization, its value is set later.
How can I compare the char* to a string? like so...

if(buffer == 'exit'){ //Will not work
}
 

if ( 0 == strcmp ( buffer, "exit" ) ) {
/ * do something */
}
If you want built-in string comparisons in C++ (i.e without calling strcmp) such as s1 == s2, then you should use the string data type.
Link to comment
Share on other sites

  • 0

Single-quote literals are for individual characters, of type char.

char c = 'a';

Double-quote literals are for characters arrays, i.e. c-style strings, of type char[].

char[] = "hello"; // creates an array of 6 characters including the null terminator

So first, you probably intended to write:

if(buffer == "exit")

But that still doesn't work, because then you're comparing two arrays, which means you're testing if they point to the same location in memory. Of course they do not (even if they happened to point at identical series of characters), so this is always false.

 

To work with c-style strings, use the functions defined in <cstring>. In this case you want strcmp or strncmp.

 

That said, in C++, a better approach is generally to use the std::string type. I suggest reading a good tutorial on arrays, strings and pointers such as this.

Link to comment
Share on other sites

  • 0
if ( 0 == strcmp ( buffer, "exit" ) ) {
/ * do something */
}
If you want built-in string comparisons in C++ (i.e without calling strcmp) such as s1 == s2, then you should use the string data type.

 

You answered my question before i could post back that i solved the issue ! haha

 

Anyways the solution was simple

if(strncmp(buffer, exit_passphrase_, bufsize) != 0){
Link to comment
Share on other sites

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.