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 :)
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");
This question already has answers here:
How do I properly compare strings in C?
(10 answers)
string comparison inside if condition malfunctioning [duplicate]
(2 answers)
Closed 5 years ago.
#include<stdio.h>
int main(){
char name[20];
scanf(" %s", name);
if (name == 'James'){
printf("Welcome James");
}else{
printf("You are not James");
}
}
Hope you got my idea. I know this doesn't work. But is there any way to do something like this?
Use
if (strcmp(name, "James") == 0)
instead of
if (name == 'James')
Man page of strcmp:
Return Value
The strcmp() and strncmp() functions return an integer less than,
equal to, or greater than zero if s1 (or the first n bytes thereof) is
found, respectively, to be less than, to match, or be greater than s2.
try: strcmp()
#include<stdio.h>
int main(){
char name[20];
scanf(" %s", name);
if (strcmp(name,"James")){
printf("Welcome James");
}else{
printf("You are not James");
}
}
Ref : How do I properly compare strings?
In C you have to use cmp string function:
strcmp(const char* s1, const char* s2);
Return values of function:
return value == 0 - s1 is equals s2
return value > 0 - s1 is longer than s2
return value < 0- s1 is smaller than s2
It is beacuse if you write:
char name_buff[20];
if (name_buff == "James")
{
...
It doesn't mean comparsion of strings but of address in memory.
So you have to use strcmp().
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;
}
I have this code sample. There is a scanf to hold the input String values from keyboard (i.e Lotus). But even if I type the word Lotus correctly It does not execute the relevant if statement. **Is there any problem with my scanf function???
#include<stdio.h>
int main()
{
char landType,houseType[100],wantToContinue,wantToContinue2;
float installment;
wantToContinue='Y';
while(wantToContinue == 'Y' || wantToContinue == 'y') {
printf("Land Type : ");
scanf(" %c",&landType);
if(landType == 'A') {
printf("Type of House: ");
scanf(" %s", houseType);
if(houseType == "Lotus") {
//this won't go inside if statement even if I type Lotus correctly
installment=4000000-500000;
printf("Monthly Installment : R.s %.2f\n",installment/120);
printf("Do you want to Continue?(Y/y or N/n) : ");
scanf(" %c",&wantToContinue2);
if(wantToContinue2 == 'Y' || wantToContinue2 == 'y') {
wantToContinue=wantToContinue2;
printf("\n");
}else{
wantToContinue='N';
}
}
}
}
}
Be careful when comparing two strings in C. You should use the strcmp function from the string.h library, like so:
if(strcmp("Lotus", houseType) == 0)
When you write if(houseType=="Lotus") you are actually comparing the base address of the two strings and not their actual content.
In C, strings cannot be compared using ==. This is because strings are not a basic data type in C, that is C does not inherently understand how to compare them - you must use a function instead.
A standard function for comparing strings in C is strcmp(), e.g.:
if (strcmp(houseType, "Lotus") == 0)
{
// do some work if the strings are equal
}
To explain further, your initial attempt to compare strings using housetype == "Lotus" actually compares the address where the first character of the character array houseType is stored with the address where the first character of the character array "Lotus" is stored.
This happens because strings in C are just arrays of characters - they are not an inherent data type, C does not, as such, understand the difference between an array of integers and an array of characters, they are all just numbers arranged contiguously somewhere in memory and it treats them as such unless you specifically use code that operates on them as strings instead.
I want to make a stock calculator with C language, and it still in progress. I make it using Microsoft Visual Studio 2015.
When I input a string(example: "refrigerator") and I print it using printf, my computer can print it. But when that string put into an if it can't continue. The progress stop at:
scanf_s("%s",stock1,sizeof(stock1));
fflush(stdin);
After that when I input "refrigerator" the if statement is not coming out.
Here is my code:
int fan, refrigerator, lpg;
int menu;
char stock1[15], stock2[15];
int total1, total2, totalstock;
int check;
printf("Type the item that you want to add\n");
scanf_s("%s",stock1, sizeof(stock1));
fflush(stdin);
if (stock1 == "refrigerator")
{
printf("How many item would you like to add?\n");
scanf_s("%d", &total1);
fflush(stdin);
}
getchar();
return 0;
}
In C you should use the strcmp function to compare strings. For example, in your case you'd compare your string to "refrigerator" in the following manner:
if(strcmp(stock1, "refrigerator") == 0)
{
/* etc */
}
There are quite a few string functions available - you should probably familiarize yourself with them.
Best of luck.
Your problem is you are comparing a string literal with a char array that the wrong way of comparing string literals with a char array you must use
if(strcmp(stock,"refrigerator")==0)
instead of
stock1=="refrigerator"
strcmp return 0 if the string 1 is identical to string 2, >0 if string 1 is greater than string 2 and <0 if string1 is less than string2.
Since you're using C language, you must use strcmp function.
strcmp function returns 0 value if both strings have the same value.
Use it this way:
if(strcmp(string,"refrigerator") == 0)
{
/*string is equal to "refrigerator"*/
} else {
/*string is not equal to "refrigerator"*/
}
Don't forget to include string.h