How to handle POST requests in c++ CGI [duplicate] - c++

This question already has answers here:
How do I properly compare strings in C?
(10 answers)
Closed 1 year ago.
int main (int argc, **argv)
{
if (argv[1] == "-hello")
printf("True\n");
else
printf("False\n");
}
# ./myProg -hello
False
Why? I realize strcmp(argv[1], "-hello") == 0 returns true... but why can't I use the equality operator to compare two C strings?

Because argv[1] (for instance) is actually a pointer to the string. So all you're doing is comparing pointers.

You can't compare strings in C with ==, because the C compiler does not really have a clue about strings beyond a string-literal.
The compiler sees a comparison with a char* on either side, so it does a pointer comparison (which compares the addresses stored in the pointers)

In C because, in most contexts, an array "decays into a pointer to its first element".
So, when you have the array "foobar" and use it in most contexts, it decays into a pointer:
if (name == "foobar") /* ... */; /* comparing name with a pointer */
What you want it to compare the contents of the array with something. You can do that manually
if ('p' == *("foobar")) /* ... */; /* false: 'p' != 'f' */
if ('m' == *("foobar"+1)) /* ... */; /* false: 'm' != 'o' */
if ('g' == *("foobar"+2)) /* ... */; /* false: 'g' != 'o' */
or automatically
if (strcmp(name, "foobar")) /* name is not "foobar" */;

Because there is no such thing as a C string.
In C, a string is usually an array of char, or a pointer to char (which is nearly the same). Comparing a pointer/array to a const array won't give the expected results.
UPDATE: what I meant by 'no C string' is, there is no string in C. What's usually referred to as a 'C string' is language independent (as 'Pascal string' is), it's the representation of strings as a null-terminated linear array of characters.

In C, string values (including string literals) are represented as arrays of char followed by a 0 terminator, and you cannot use the == operator to compare array contents; the language simply doesn't define the operation.
Except when it is the operand of either the sizeof or & operators, or when it is a string literal being used to initialize another array in a declaration, an expression with type "N-element array of T" will have its type implicitly converted (decay) to type "pointer to T", and the value of the expression will be the address of the first element of the array.
So when you write
if (argv[1] == "-hello")
the compiler implicitly converts the expression "-hello" from type "7-element array of char" to "pointer to char" (argv[1] is already a pointer type), and the value of the expression is the address of the character '-'. So what == winds up comparing are two pointer values, which are (most likely) never going to be equal since "-hello" and argv[1] (most likely) occupy different regions in memory.
This is why you have to use library functions like strcmp() to compare string values.

Because C strings dont exist as such. They are char arrays ending in a \0.
The equality operator == will test that the pointer to the first element of the array are the same. It wont compare lexicographically.
On the other hand "-hello" == "-hello" may return non zero, but that doesn't mean that the == operator compares lexicographycally. That's due to other facts.
If you want to compare lexicographycally, you can always
#define STR_EQ(s1,s2) \
strcmp(s1,s2) == 0
Reading harder I see that you tagged as c++. So you could
std::string arg1 ( argv[1] );
if (arg1 == "-hello"){
// yeahh!!!
}
else{
//awwwww
}

Strings are not native types in C. What you are comparing in that example are two pointers. One to your first argument, and the other is a static character array with the contents of "-hello".
You really want to use strncmp or something similar.

When you're using ==, you're comparing pointers. That is, it will return true if the two operands refer to the same string in memory. Therefore, it's unsuitable for use in comparing strings lexicographically.

Because C strings are array of characters. Arrays are simply pointers to the first element in the array, and when you compare two pointers using == it compares the memory address they point to, not the values that they point to.

Related

char type declaration and verification

How to check the char type? my variable input need to be a char, cause it contain letters and numbers.
If I use string instead of char, I don't have error with while, but I have error with cin.getline(input,10)
char input[10];
while(input != "1") //Error: result of comparison against a string literal is unspecified(use strncmp //instead)
{
cin.getline(input, 10);
}
In expressions (with rare exception as for example when they are used in sizeof operator) arrays are implicitly converted to pointers to their first elements.
In this condition
while(input != "1")
there are compared addresses of the first character of the array input and of the first character of the string literal "1".
Use instead standard C function strcmp declared in the header <cstring>.
Pay attention to that in your code snippet the array input is not initialized. So before comparing it with something you have to initialize it.

Difference in comparing string .c_str() and normal string

I wanted to know what the difference between the two codes is. When I use .c_str() it does not work
std::vector<std::pair<std::string, std::string> >::iterator it
for(;it!=MySet.end();++it)
{
if(std::get<1>(*it).c_str()=="PAUSE") //Why it works only with std::get<1>(*it) and not with std::get<1>(*it).c_str()
{
TempDefaultVan = std::get<0>(*it).c_str();
}
}
So basically what is happening is .c_str() is returning a const char*. This will cause operator == to compare pointers and not the string's content. Since both of these are clearly not pointing to the same memory location (since "PAUSE" is a string literal), this will always be false.
std::get<1>(*it) returns an object of type std::string. This class has overload operator == to compare objects of type std::string with character arrays.
std::get<1>(*it).c_str() returns a character array. Arrays have no the comparison operator. To compare character arrays you should use standard C function std::strcmp
So you could write
if( std::strcmp( std::get<1>(*it).c_str(), "PAUSE" ) == 0 )
If you will write simply as
if(std::get<1>(*it).c_str()=="PAUSE")
then the compiler will compare two pointers because it converts arrays to pointers to their first elements in such expressions. And as the result this expression will be equal always to false if the arrays occupy different areas of memory.
This code:
std::get<1>(*it).c_str()=="PAUSE"
is comparing two const char *, which both point to strings. This is not what you usually want when comparing strings, as it will only evaluate to true when they point to the same place in memory.
This code:
std::get<1>(*it)=="PAUSE"
Will use std::string::operator== to compare the contents of the std::string std::get<1>(*it) with the contents of "PAUSE". If you instead had two char * values, you could use strcmp, but since you have a std::string, this is the best way to make the comparison (and, as you say, "it works").

comparing a char to a const char * [duplicate]

This question already has answers here:
c++ compile error: ISO C++ forbids comparison between pointer and integer
(5 answers)
Closed 5 years ago.
string line = "blerdy blah";
for (int i = 0; i < string.size(); i++)
{
line[i] != "n";
}
With this I get the error "cannot convert from char to const char *"
If I replace the last line with
line[i] != *"n";
It works. I get why in one sense, I'm dereferencing a pointer. What I don't get is why it's a pointer in the first place. Is any char written like this actually a pointer to one char somewhere? Like the program has one set of every symbol somewhere and this is what I'm pointing to?
If this is the case, can I do silly things like make the 'n' pointer point to something else?
You have to compare char with char in this case:
line[i] != 'n';
When you say *"n" you actually dereference the first element of the char array with n and \0 elements inside it, which gives you n, that's why it works, but you don't want to write it like that.
"n" is not a character literal, it is a string literal. You want 'n'.
"n" is a char array (string). While 'n' is a char.
"n" is a so called string literal, which has the type const char[2]. string::operator[] (actually basic_string<char>::operator[] returns a const char& or char& depending on the picked overload (the second one in this case). You cannot compare those types. What you want want to compare the result of operator[] to is a character literal, which is written as 'n'.
For your second question
"n" has type const char[2], dereferencing it gives you a char (the first character in the array pointed to). This is equivalent to "n"[0].
Change "n" to 'n'. The difference is that the former is a const char* whereas the latter is char. Since you want to compare one char to another, the latter is the correct form to use.
Why and how this works
Start with "n": lexically it is a null-terminated string literal, which means that the compiler will end up treating it as a char* pointing to a section of memory that holds the string "n".
So when you write *"n", what happens is that you are dereferencing a char* that points to "n", which means that the result of the expression will be 'n' (of type char). That's why the comparison to line[i] (which is also a char) works.
This pointer to "n" is a compile-time constant (so you can't change it) and in all likelihood will point to a read-only memory page (so you won't be able to change what it points to at runtime either).
What you should do instead
line[i] != 'n'; // compare char to char

Compare equality of char[] in C

I have two variables:
char charTime[] = "TIME";
char buf[] = "SOMETHINGELSE";
I want to check if these two are equal... using charTime == buf doesn't work.
What should I use, and can someone explain why using == doesn't work?
Would this action be different in C and C++?
char charTime[] = "TIME"; char buf[] = "SOMETHINGELSE";
C++ and C (remove std:: for C):
bool equal = (std::strcmp(charTime, buf) == 0);
But the true C++ way:
std::string charTime = "TIME", buf = "SOMETHINGELSE";
bool equal = (charTime == buf);
Using == does not work because it tries to compare the addresses of the first character of each array (obviously, they do not equal). It won't compare the content of both arrays.
In c you could use the strcmp function from string.h, it returns 0 if they are equal
#include <string.h>
if( !strcmp( charTime, buf ))
In an expression using == the names of char arrays decay into char* pointing to the start of their respective arrays. The comparison is then perform in terms of the values of the pointers themselves and not the actual contents of the arrays.
== will only return true for two pointers pointing to the same location and false otherwise, even if they are pointing to two arrays with identical contents.
What you need is the standard library function strcmp. This expression evaluates as true if the arrays contain the same contents (up to the terminating null character which must be present in both arrays fro strcmp to work safely).
strcmp(charTime, buf) == 0
Check them in a for loop. Get the ASCII numbers for each char once they change they're not equal.
You are checking the identity charTime and buf. To check the equality, loop over each character in one array and compare them with the related character in the other array.

Comparing character arrays and string literals in C++

I have a character array and I'm trying to figure out if it matches a string literal, for example:
char value[] = "yes";
if(value == "yes") {
// code block
} else {
// code block
}
This resulted in the following error: comparison with string literal results in unspecified behavior. I also tried something like:
char value[] = "yes";
if(strcmp(value, "yes")) {
// code block
} else {
// code block
}
This didn't yield any compiler errors but it is not behaving as expected.
Check the documentation for strcmp. Hint: it doesn't return a boolean value.
ETA: == doesn't work in general because cstr1 == cstr2 compares pointers, so that comparison will only be true if cstr1 and cstr2 point to the same memory location, even if they happen to both refer to strings that are lexicographically equal. What you tried (comparing a cstring to a literal, e.g. cstr == "yes") especially won't work, because the standard doesn't require it to. In a reasonable implementation I doubt it would explode, but cstr == "yes" is unlikely to ever succeed, because cstr is unlikely to refer to the address that the string constant "yes" lives in.
std::strcmp returns 0 if strings are equal.
strcmp returns a tri-state value to indicate what the relative order of the two strings are. When making a call like strcmp(a, b), the function returns
a value < 0 when a < b
0 when a == b
a value > 0 when a > b
As the question is tagged with c++, in addition to David Seilers excellent explanation on why strcmp() did not work in your case, I want to point out, that strcmp() does not work on character arrays in general, only on null-terminated character arrays (Source).
In your case, you are assigning a string literal to a character array, which will result in a null-terminated character array automatically, so no problem here. But, if you slice your character array out of e. g. a buffer, it may not be null-terminated. In such cases, it is dangerous to use strcmp() as it will traverse the memory until it finds a null byte ('\0') to form a string.
Another solution to your problem would be (using C++ std::string):
char value[] = "yes";
if (std::string{value} == "yes")) {
// code block
} else {
// code block
}
This will also only work for null-terminated character arrays. If your character array is not null-terminated, tell the std::string constructor how long your character array is:
char value[3] = "yes";
if (std::string{value, 3} == "yes")) {
// code block
} else {
// code block
}