This question already has answers here:
How do I properly compare strings in C?
(10 answers)
Closed 6 years ago.
hey guys ok i wrote this code which would check if a get request is proper but at the last comparison it doesn't give me the expected result thank you in advance the problem is in the last if statement it return false when it should return true
#include <stdio.h>
#include <string.h>
int main()
{
char* string="GET /cats.html HTTP/1.1\r\n";
if(strncmp(string,"GET ",4)==0)
{
printf("hello");
if(string[4]=='/')
{
printf(",\n");
char* string1=strchr(string,'.');
string1=strchr(string1,' ');
printf("%s",string1);
if(string1!=NULL)
{
if(*string1==" HTTP/1.1\r\n")
{
printf("world\n");
}
}
}
}
}
The line:
if(*string1==" HTTP/1.1\r\n")
does not compare whether two strings are equal.
type of string1 is char*. Hence type of *string1 is char.
Hence, you are comparing a char with a char const*, which is far from what you expected.
Even using
if(string1==" HTTP/1.1\r\n")
will not give you the expected result since it will compare two pointers for equality, which will be false in this use case all the time.
What you need to use is the library function to compare two strings.
if( strcmp(string1, " HTTP/1.1\r\n") == 0)
Because you are not comparing strings, you are comparing pointers to strings.
The proper comparison would be:
if(!strcmp(string1," HTTP/1.1\r\n")) {
...
}
Related
This question already has answers here:
Case Insensitive String Comparison in C
(12 answers)
Closed 2 years ago.
I have a code:
int main()
{
printf("to exit the program type \"exit\":");
char s[40];
scanf("%s",s);
if(strcmp(s,"exit")==0)
{
exit(0);
}
else
{
int n;
printf("wrong");
}
return 0;
}
I want to when I enter "ExIt" it works.
how can i change that?
you can use tolower() in C, but it works for char, so maybe you need to itterate over s string and putting every char to lower case.
use stricmp instead of strcmp.
More letters to hit 30
This question already has answers here:
How do I properly compare strings in C?
(10 answers)
Closed 5 years ago.
char str[6];
do
{
printf("Enter the string you wanna check:");
scanf("%s", str);
}
while(str != "exit");
Why does this not work?
str will never equal "exit", because you're comparing the addresses of two different sections of memory. You probably want to compare the contents of the strings, for which there is a function strcmp().
"exit" is a char[5] generated by the compiler at some address in the data segment. This address is definitely different from the address of str, as two different objects cannot occupy the same location in memory.
The != operator between expressions of type char[] compares two pointers. These two pointers are the address of "exit" and the address of str, which, as I have already explained, will never be equal.
So, the expression str != "exit" will never evaluate to true. Which brings us to another point: your compiler should have issued a warning about this condition being always false. Which means that you are trying to program without -Wall. Don't do this, you are never going to get very far. Always use the highest warning level, and when you see warnings, always fix them.
To correct the problem, do as user3121023 suggested in a comment, and use strcmp() to compare strings.
The short answer is: it does not work because you must use strcmp(str, "exit") to compare the strings and loop for as long as the return value of strcmp() is not 0.
The long answer is: there are more problems in this little code fragment:
The array into which you read a word is very short and you do not limit the number of characters scanf() is likely to store there. Any user input longer than 5 non space characters will cause undefined behavior.
You do not check the return value of scanf(). A premature end of file, such as redirecting input from an empty file, will cause an infinite loop.
Here is how the code can be written in a safer way:
#include <stdio.h>
int main(void) {
char str[80];
for (;;) {
printf("Enter the string you wanna check:");
if (scanf("%79s", str) != 1 || strcmp(str, "exit") == 0)
break;
}
return 0;
}
As suggested above, use strcmp from the <string.h> header file.
char str[6];
do {
printf("Enter the string you wanna check:");
scanf("%s", str);
} while(!strcmp(str, "exit"));
Try :
#include <stdio.h>
#include <string.h>
int main() {
char str[6];
do
{
printf("Enter the string you wanna check:");
scanf("%s", str);
}
while(strcmp(str, "exit") != 0);
return 0;
}
This question already has answers here:
How do I properly compare strings in C?
(10 answers)
Closed 7 years ago.
So I am trying to learn c however I can't figure out why this code won't run properly.
#include <stdio.h>
#include <stdlib.h>
int main()
{
char userName[25];
char myName[25] = "myName";
printf("Please enter your name: \n");
scanf("%s", userName);
if(userName == myName)
{
printf("Congratulations your name is myName!!!");
}
else
{
printf("Your name is %s how disappointing...", userName);
}
return 0;
}
The problem is that the if statement never seems to return true.
Can anyone help me with this?
This line is comparing the locations of the strings, which are different, since you are comparing two different strings.
if(userName == myName)
The correct test in C is to use a library function.
#include <string.h>
...
if(strcmp(userName,myName) == 0)
In C, you should use strcmp() to compare two strings.
So change this:
if(userName == myName)
to this:
if(strcmp(userName,myName) == 0)
You cannot compare strings like that. What you are doing is comparing the pointers to the respective stings(which are obviously different).
So,
userName == myName
won't work here. You may use string functions to compare the two strings.
The statement if(userName == myName) will not work the way you are expecting it to. Use the strcmp() function to compare two strings.
Use strcmp / strncmp declared in string.h to compare strings; in your program the values you are comparing (after conversion) are pointer values.
This question already has answers here:
Using the equality operator == to compare two strings for equality in C [duplicate]
(9 answers)
Closed 8 years ago.
In the following working code; instead of using *tofind, if I directly use the comparison
if(*argv[i] == "and")
it fails.
Why would that be?
/**
* Find index of the word "and"
* ./a.out alice and bob
*/
int main(int argc, char **argv) {
int i = 0;
char *tofind = "and";
while (argv[i] != NULL) {
if(*argv[i] == *tofind) {
printf("%d\n", i + 1);
break;
}
++i;
}
return 0;
}
if(*argv[i] == "and") shouldn't compile, I think you mean if (argv[i] == "and"), that would compare the pointers of the two, not the string content.
if (*argv[i] == *tofind) doesn't work as you expected either, it only compares the first character.
To compare strings, use strcmp():
if (strcmp(argv[i], tofind) == 0)
A "char*" is officially a pointer to a single char, for example to find points to a letter 'a'. You know that there are two more chars and a nul char, but officially it points to a single char.
Therefore, *argv[i] is the first character of an argument, and *tofind is always the letter 'a', so your code checks if the first character of an argument is an 'a'. Look at the strcmp function, which compares whole strings.
look at the type of
*argv[i] //its type is char
and of "and"
"and" //its type is const char * as it is decayed into pointer
so thats why you are unable to compare them.
while the type of
*tofind
is char and you can now compare the two.for more details see FAQs section 6.
This question already has answers here:
C Strings Comparison with Equal Sign
(5 answers)
Closed 9 years ago.
i've written some simple code as an SSCCE, I'm trying to check if string entered is equal to a string i've defined in a char pointer array, so it should point to the string and give me a result. I'm not getting any warnings or errors but I'm just not getting any result (either "true" or "false")
is there something else being scanned with the scanf? a termination symbol or something? i'm just not able to get it to print out either true or false
code:
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#define LENGTH 20
//typedef char boolean;
int main(void)
{
const char *temp[1];
temp[0] = "true\0";
temp[1] = "false\0";
char var[LENGTH];
printf("Enter either true or false.\n");
scanf("%s", var);
if(var == temp[0]) //compare contents of array
{
printf("\ntrue\n");
}
else if(var == temp[1]) //compare contents of array
{
printf("\nfalse\n");
}
}
const char *temp[1];
This defines tmp an array that can store 1 char* element.
temp[0] = "true\0";
Assigngs to the first element. This is okay.
temp[1] = "false\0";
Would assign to the second element, but temp can only store one. C doesn't check array boundaries for you.
Also not that you don't have to specify the terminating '\0' explicitly in string literals, so just "true" and "false" are sufficient.
if(var == temp[0])
This compares only the pointer values ("where the strings are stored"), not the contents. You need the strcmp() function (and read carefully, the returned value for equal strings might not be what you expect it to be).
Use strcmp for comparing strings:
#include <stdio.h>
int main(void)
{
const int LENGTH = 20;
char str[LENGTH];
printf("Type \"true\" or \"false\:\n");
if (scanf("%19s", str) != 1) {
printf("scanf failed.");
return -1;
}
if(strcmp(str, "true") == 0) {
printf("\"true\" has been typed.\n");
}
else if(strcmp(str, "false") == 0) {
printf("\"false\" has been typed.\n");
}
return 0;
}
and also note that:
string literals automatically contain null-terminating character ("true", not "true\0")
const int LENGTH is better than #define LENGTH since type safety comes with it
"%19s" ensures that no more than 19 characters (+ \0) will be stored in str
typedef char boolean; is not a good idea
unlikely, but still: scanf doesn't have to succeed
and there is no #include <iostream> in c :)
== checks for equality. Let's see what you're comparing.
The variable var is declared as a character array, so the expression var is really equivalent to &var[0] (the address of the first character in the var array).
Similarly, temp[0] is equivalent to &temp[0][0] (the address of the first character in the temp[0] array).
These addresses are obviously different (otherwise writing var would automatically write temp[0] as well), so == will always return 0 for your case.
strcmp, on the other hand, does not check for equality of its inputs, but for character-by-character equality of the arrays pointed to by its inputs (that is, it compares their members, not their addresses) and so you can use that for strings in C. It's worth noting that strcmp returns 0 (false) if the strings are equal.