C String Comparison Failure? [duplicate] - c

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
C String — Using Equality Operator == for comparing two strings for equality
I have the following code;
#include <stdio.h>
#define MAXLINE 2600
char words[4][MAXLINE];
int i;
int main(){
printf("Enter menu option: ");
scanf("%s", words[i]);
printf ("\n %s was entered!", words[i]);
if (words[i]=="help"){
printf("\nHelp was requested");
}
else
{
printf("\nCommand not recognized!");
}
}
The array evaluation in the if statement isn't working. I am obviously doing something wrong. Can someone explain to me what?

You are comparing words[i] and "help" for pointer equality, not string equality. I think you meant: if (strcmp(words[i], "help") == 0) {

In C, strings (sequences of characters) are treated as arrays of characters. As a result, you shouldn't compare arrays using the == operator.
The array braces [] are just syntactic sugar to hide the pointer arithmetic that's going on under the hood. In general, arr[i] is identical to *(arr + i). Using this information, let's take a look at your comparison:
words[i] -> *(words + i), which is a pointer to an array of characters.
If you want to compare strings, use strncmp.

Related

Error in string do while [duplicate]

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;
}

C cannot figure out if statement [duplicate]

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.

Searching for an element in 2D array, C programming

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;
}

Why directly comparing string fails, but succeeds using char* [duplicate]

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.

Comparing two strings in C? [duplicate]

This question already has answers here:
How do I properly compare strings in C?
(10 answers)
Closed 4 years ago.
This code is not working as the comparison is not being done. Why?
All names get past the if.
printf("Enter Product: \n");
scanf("%s", &nameIt2);
printf("Enter Description: \n");
scanf("%s", &descriptionI);
printf("Enter Quantity: \n");
scanf("%d", &qtyI);
printf("Enter Order Quantity: \n");
scanf("%s", &ordqtyI);
while (fscanf(fp4, "%s %s %d %s\n", &namet2, &description2, &qty2, &ordqty2) != EOF){
if(namet2 != nameIt2)
fprintf(fpt2, "%s %s %d %s\n", &namet2, &description2, qty2, &ordqty2);
}
To compare two C strings (char *), use strcmp(). The function returns 0 when the strings are equal, so you would need to use this in your code:
if (strcmp(namet2, nameIt2) != 0)
If you (wrongly) use
if (namet2 != nameIt2)
you are comparing the pointers (addresses) of both strings, which are unequal when you have two different pointers (which is always the case in your situation).
For comparing 2 strings, either use the built in function strcmp() using header file string.h
if(strcmp(a,b)==0)
printf("Entered strings are equal");
else
printf("Entered strings are not equal");
OR you can write your own function like this:
int string_compare(char str1[], char str2[])
{
int ctr=0;
while(str1[ctr]==str2[ctr])
{
if(str1[ctr]=='\0'||str2[ctr]=='\0')
break;
ctr++;
}
if(str1[ctr]=='\0' && str2[ctr]=='\0')
return 0;
else
return -1;
}
You are currently comparing the addresses of the two strings.
Use strcmp to compare the values of two char arrays
if (strcmp(namet2, nameIt2) != 0)
You try and compare pointers here, not the contents of what is pointed to (ie, your characters).
You must use either memcmp or str{,n}cmp to compare the contents.
You need to use strcmp:
strcmp(namet2, nameIt2)
The name of the array indicates the starting address. Starting address of both namet2 and nameIt2 are different. So the equal to (==) operator checks whether the addresses are the same or not. For comparing two strings, a better way is to use strcmp(), or we can compare character by character using a loop.
To answer the WHY in your question:
Because the equality operator can only be applied to simple variable types, such as floats, ints, or chars, and not to more sophisticated types, such as structures or arrays.
To determine if two strings are equal, you must explicitly compare the two character strings character by character.
if(strcmp(sr1,str2)) // this returns 0 if strings r equal
flag=0;
else flag=1; // then last check the variable flag value and print the message
OR
char str1[20],str2[20];
printf("enter first str > ");
gets(str1);
printf("enter second str > ");
gets(str2);
for(int i=0;str1[i]!='\0';i++)
{
if(str[i]==str2[i])
flag=0;
else {flag=1; break;}
}
//check the value of flag if it is 0 then strings r equal simple :)

Resources