using the following program in C, the string comparison is not working:
#include<stdio.h>
#include<string.h>
int main(){
char ch[]="ABC";
printf("%d \n", strlen(ch)); // output 3
printf("%d \n", strlen("ABC")); // output 3
if(strcmp("ABC",ch)){
printf("\n Matched");
}else{
printf("\n Not matched"); // this will be output
}
if("ABC" == ch){
printf("\n Matched");
}else{
printf("\n Not matched"); // this will be output
}
}//ends main
the output is:
3
3
Not matched
Not matched
Why the string is not matching?
With "ABC" == ch you compare two pointers, you don't compare what the pointers are pointing to. And these two pointers will never be equal.
And the strcmp function returns zero if the strings are equal. Zero is considered "false" in C, and all non-zero values are "true".
String literals in C are really arrays of (read-only) characters, including the terminator. As all arrays they decay to pointers to their first elements when they are used in most expressions.
It would work if you change the double qoutes to single qoutes: "ABC" to 'ABC'
Related
I'm a rookie programmer trying to run a simple code on VS code.
#include<stdio.h>
int main()
{
char* a;
printf("Enter a char");
scanf("%s",&a);
if (a = "yes")
{
printf("Number is 30");
}
else if (a = "no")
{
printf("Number is 50");
}
else{
printf("oops");
}
return 0;
}
I guess looking at the code you guys can figure out what I'm trying to do, if the user enters "yes", a specific sentence need to be displayed and similarly for "no".
The problem here is whatever I write in the input, it will always print the first statement, "Number is 30". I've tried running similar codes but ended up with the same output.
If possible, please explain me how to use char,strings,arrays with if-else statements.
There are several misunderstandings in the posted code.
First there is a misunderstanding of char versus string. A char is for instance a single letter, a single special character like ., ;, etc. (see note1) while a string is a serie of chars. So
'y' is a char
"yes" is a string
You print "Enter a char" but from the code it's obvious that you really want "Enter a string".
This leads to the next problem. To input a string using scanf you need to pass a "pointer to char". Your code pass "a pointer to pointer to char" due to the &. Further the passed pointer must point to some memory. So you need:
char a[10]; // Make it an array of char so that it can hold a string
printf("Enter a string, max 9 characters");
scanf("%9s", a); // No & before a and width specifier used to avoid buffer overflow
Now this part
if (a = "yes")
is not the way to compare two strings in C. For that you need the function strcmp - like:
if (strcmp(a, "yes") == 0)
Putting it together it's like:
int main()
{
char a[10];
printf("Enter a string, max 9 characters");
scanf("%9s", a);
if (strcmp(a, "yes") == 0){
printf("Number is 30");
}
else if (strcmp(a, "no") == 0)
{
printf("Number is 50");
}
else
{
printf("oops");
}
return 0;
}
That said, I don't understand why you print stuff like: "Number is 30" but that's kind of irrelevant here.
note1: The type char is actually an integer type, i.e. a number, but the common use is to map these numbers to characters using ASCII encoding.
There are different ways to initialize a variable to access C string.
char *char_ptr = "Hello";
This initializes char_ptr to point to the first character of the read-only string "Look Here".A C string initialized through a character pointer cannot be modified. When a C string is initialized this way, trying to modify any character pointed to by char_ptr is undefined behaviour. An undefined behaviour means that when a compiler encounters anything that triggers undefined behaviour, it is allowed to do anything it seems appropriate.
A more convenient way to define strings that can be modified is to use:
char str[];
This way you can modify any character in the C string
p.s you also need to use strcmp() for the if statement
You can take string input in C using
scanf(ā%sā, str);
And to compare the string you need to use:
strcmp(str1, "yes");
I want to initialize a character array, then pass it to a function that parses command line arguments. I want this function to overwrite the character array to the input argument from the command line, then perform some syntactic checks on individual characters within that array.
I'm not showing the original code I've been working on, but I think I have a sample program to highlight what I'm struggling with
#include <stdio.h>
#include <stdlib.h>
void changeArray(char **arr){
printf("Array is %s\n",*arr);
printf("This character is %c\n",*arr[0]);
printf("This character is %c\n",*arr[1]); //segmentation fault here
printf("This character is %c\n",arr[2]);
printf("This character is %c\n",arr[3]);
printf("This character is %c\n",arr[4]);
*arr = "bingo";
printf("Array is %s\n",*arr);
printf("This character is %c\n",arr[0]);
printf("This character is %c\n",arr[1]);
printf("This character is %c\n",arr[2]);
printf("This character is %c\n",arr[3]);
printf("This character is %c\n",arr[4]);
}
int main(int argc, const char* argv[]){
char *blah = "hello";
printf("Array is %s\n",blah);
printf("This character is %c\n",blah[0]);
printf("This character is %c\n",blah[1]);
printf("This character is %c\n",blah[2]);
printf("This character is %c\n",blah[3]);
printf("This character is %c\n",blah[4]);
changeArray(&blah);
printf("This character is %c\n",blah[0]);
printf("This character is %c\n",blah[1]);
printf("This character is %c\n",blah[2]);
printf("This character is %c\n",blah[3]);
printf("This character is %c\n",blah[4]);
printf("Array is %s\n",blah);
return 0;
}
This is the program output, the first index into the character array seems to print the letter 'h' like I would expect, but any other index causes me to go out of bounds:
Array is hello
This character is h
This character is e
This character is l
This character is l
This character is o
Array is hello
This character is h
Segmentation fault
You have a problem with the order of operations. Operator precedence states that the [] operation occurs before the pointer is dereferenced, so you've essentially advanced to the second pointer in an array of character pointers, and then dereferenced the first item. You want to run (*arr)[1] to treat arr as a pointer to an array, rather than an array of pointers.
https://en.cppreference.com/w/cpp/language/operator_precedence
The precedence of the array subscript operator ([]) is higher than that of the pointer dereference operator (*). So *arr[1] is equivalent to *(arr[1]). But arr only has a single element (it's just the address of blah), so arr[1] isn't a valid thing to access (let alone to dereference).
To achieve what you want, you'll either have to use parentheses ((*arr)[1]) or use a subscript operator instead of a dereference operator for the top-level dereference (arr[0][1]).
I want to access strings from an array, just like one can access integers from arrays, say A={1,2,3} then upon calling A[0] one would get 1. Similarly what should be done for strings such that A={a,b,c} so upon calling A[0] I get a.
I tried this for the input,
char in[1000];
for (i=0;i<5;i++)
{
in[i]="A";
printf("in is %f",in[i]);
}
but I am getting a warning assignment makes integer from pointer without a cast
Since you are making a character array, you need to supply a character value to it.
Change your code to
in[i]='A'
printf("in is %c",in[i]);
Hope this helps :)
You should use %s for strings not %f.
%s - Strings (character arrays in case of C)
%c - Characters
%f - floats
%d - int
%ls - long int
Your example :
int i=0;
char in[1000];
for (i=0;i<5;i++)
{
in[i]='A';
printf("in is %c\n",in[i]);
}
Sample code : example
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 :)
Edit: Changed title to reflect both methods in post.
I'm trying to compare two strings in c language as below but for some reason it's always printing that both strings are not equal
#include <stdio.h>
#include <string.h>
int main()
{
/* A nice long string */
char test[30]="hellow world";
char test2[30];
// to copy string from first array to second array
strcpy(test2, test);
/* now comparing two stering*/
if(strcmp(test2, test))
printf("strigs are equal ");
else
printf("not equal \n");
printf("value of first string is %s and second string is %s",test,test2);
printf("length of string1 is %zu and other string is %zu ",strlen(test2),strlen(test2));
}
I'm always getting output as
not equal
value of first string is hellow world and second string is hellow worldlength of string1 is 12 and other string is 12
Your problem is with how you're using strcmp. strcmp returns 0 (which evaluates as false) when the strings are equal (and returns a positive number when the strings are "in order" and a negative number when they're "out of order").
strcmp returns 0 when two strings are the same, and 0 evaluates to false in C. Try:
if(strcmp(test2, test)==0)
As per C++ reference
Return value of strcmp
-A zero value indicates that both strings are equal.
-A value greater than zero indicates that the first character that does not match has a greater value in str1 than in str2; And a value less than zero indicates the opposite.
Alter your condition to if(!strcmp(test2, test)) and it should work.
strcmp() returns 0 if the strings are equal. See, for example, http://www.cplusplus.com/reference/clibrary/cstring/strcmp/
strcmp() returns 0 on equality
man strcmp: "The strcmp() function compares the two strings s1 and s2. It returns an integer less than, equal to, or greater than zero if s1 is found, respectively, to be less than, to match, or be greater than s2."
strcmp return 0 if the given two strings are equal.
I have also fixed few spelling mistakes and in the last printf() you have called strlen(test2) two times! - correct that as well
#include <stdio.h>
#include <string.h>
int main()
{
/* A nice long string */
char test[30]="hello world";
char test2[30];
// to copy string from first array to second array
strcpy(test2, test);
/* now comparing two stering*/
if(!strcmp(test2, test))
printf("strigs are equal \n");
else
printf("not equal \n");
printf("value of first string is %s \nsecond string is %s \n", test, test2);
printf("length of string1 is %zu \nsecond string is %zu \n",strlen(test), strlen(test2));
return 0;
}
Output:
$ ./a.out
strigs are equal
value of first string is hello world
second string is hello world
length of string1 is 11
second string is 11
$