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.
Related
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 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")) {
...
}
I'm a noob at C programming and I'm having some difficulties making a string list and searching for a specific element.
#include <stdio.h>
#include <string.h>
# define MAX 6
int main(){
char word[MAX];
char x[MAX][20];
int i;
strcpy(x[0], "One");
strcpy(x[1], "Two");
strcpy(x[2], "Three");
strcpy(x[3], "Four");
strcpy(x[4], "Five");
strcpy(x[5], "Six");
printf("%s", "Search:");
scanf("%s", word);
for (i=0; i<6; i++) {
if (x[i] == word) {
printf("%s", "Found a match!");
}
}
return 0;
}
It's never executing the statement present in the if block (i.e, printf("Found a match!")) . Any idea why it is not executing the above mentioned statement?
Thanks!
Use
if(strcmp(x[i],word) == 0)
printf("Found match\n");
== can't be used to compare strings as you are doing it.
This only compares the pointers and not the strings
It never returns "Found a match!". Any idea why?
Reason:
In C, array names are converted to pointers to their first elements ( with some exceptions there). x[i] == word is comparing two pointers instead of comparing strings. Since the base addresses of both arrays are different, comparison returns a false value.
Correction:
Use strcmp to compare two strings.
This
if (x[i] == word)
should be
if (strcmp(x[i], word) == 0)
In c a predefined function is present in string.h library it is strcmp as stated by other users function int strcmp(const char *str1, const char *str2) compares the string pointed to bystr1 to the string pointed to by str2.u can write your own function for comparing strings and use it.
I want you to conceptually understand why we can't use == in c unlike c++ as c don't contain anything like string class(c is purely procedural) so that u can create object of it and use it.hence c uses char array to represent a string .if u examine ur code x[i] == word compares starting addresses of char arrays/strings x[i],word. I believe u understood the concept . now I want to explain that u can use pointers here i.e
if (*x[i] == *word)
printf("Found a match!");
Works fine as u can understand that here we are comparing two strings directly by pointing to their address locations.sorry if I have provided unwanted info due to my inexperience in SO as this my first answer in SO.
use strcmp() function for comparing two string. when two string is match its result is 0.
so you can change like :
if ( ! strcmp(word,x[i]) ) // when match result will be `! 0 = 1`
printf("Found Match\n");
in the C programming language, the == operator is not working for comparing strings(as others wrote before me). I advice to try using a really nice feature in C++ called string. It is builded in the standard library, and with this, you can use the == operator for comparing.
#include <iostream>
using namespace std;
int main(void)
{
string a = "Apple";
if( a == "Apple" ) cout << "This is working" << endl;
}
This question already has answers here:
strcmp on a line read with fgets
(6 answers)
Closed 9 years ago.
I'm trying to get a string input from the user and then run different functions depending on the input they've entered.
For example, say I asked, "What is your favorite fruit?" and I want the program to comment depending on what they enter...I'm not sure how to do this. Here's what I have so far:
#include <stdio.h>
#include <string.h>
char fruit[100];
main() {
printf("What is your favorite fruit?\n");
fgets (fruit, 100, stdin);
if (strcmp(fruit, "apple")) {
printf("Watch out for worms!\n");
}
else {
printf("You should have an apple instead.\n");
}
}
When I run the program, no matter what I enter, it never does the else statement.
Thanks for your help!
Note two things in your code:
fgets keeps the trailing '\n'. the associated char in fruit should be replaced with a '\0' before comparing with the string "apple".
strcmp return 0 when two strings are the same, so the if clause should be changed based on what you mean.(The fruit and "apple" be equivalent in the if clause)
Standard usage of C main function is int main(){ return 0;}
The revised code:
#include <stdio.h>
#include <string.h>
char fruit[100];
int main() {
printf("What is your favorite fruit?\n");
fgets (fruit, 100, stdin);
fruit[strlen(fruit)-1] = '\0';
if (strcmp(fruit, "apple") == 0) {
printf("Watch out for worms!\n");
}
else {
printf("You should have an apple instead.\n");
}
return 0;
}
Change the if condition to the following:
if(strcmp(fruit,"apple") == 0)
strcmp returns 0 strings if match. You should always compare the result using == operator
strcmp returns 0 if the inputs match, some value>0 if the left is "greater" than the right, some value<0 if the left is "lesser" than the right. So usually you want to simply test for equality with strcmp(...)==0. But there is also the clever version: !strcmp(...). Even if you don't use this style, it's useful to learn to recognize it.
And remember that fgets does not remove the newline character '\n' from the string.
This question already has answers here:
Comparing two strings in C? [duplicate]
(8 answers)
Closed 3 years ago.
I want to test and see if a variable of type "char" can compare with a regular string like "cheese" for a comparison like:
#include <stdio.h>
int main()
{
char favoriteDairyProduct[30];
scanf("%s",favoriteDairyProduct);
if(favoriteDairyProduct == "cheese")
{
printf("You like cheese too!");
}
else
{
printf("I like cheese more.");
}
return 0;
}
(What I actually want to do is much longer than this but this is the main part I'm stuck on.)
So how would one compare two strings in C?
You're looking for the function strcmp, or strncmp from string.h.
Since strings are just arrays, you need to compare each character, so this function will do that for you:
if (strcmp(favoriteDairyProduct, "cheese") == 0)
{
printf("You like cheese too!");
}
else
{
printf("I like cheese more.");
}
Further reading: strcmp at cplusplus.com
if(strcmp(aString, bString) == 0){
//strings are the same
}
godspeed
if(!strcmp(favoriteDairyProduct, "cheese"))
{
printf("You like cheese too!");
}
else
{
printf("I like cheese more.");
}
Have a look at the functions strcmp and strncmp.
You can't compare array of characters using == operator. You have to use string compare functions. Take a look at Strings (c-faq).
The standard library's strcmp function compares two strings, and returns 0 if they are identical, or a negative number if the first string is alphabetically "less than" the second string, or a positive number if the first string is "greater."