I need to compare 3 strings to 1 string.
I am currently using the code below. The seatclass is entered by the user.
char first[10] = "FC";
char econ[10] = "EC";
char eandf[10]= "FC&EC";
if ((seatclass==first)||(seatclass==econ)||(seatclass==eandf))
{
printf("win");
}
else
{
printf("This is not a seatclass choose again");
getchar();
}
However when I enter FC or any other random value I always get
This is not a seatclass choose again
You need to use strcmp to compare in C.
Here is how you can do the comparison :
char first[10] = "FC";
char econ[10] = "EC";
char eandf[10]= "FC&EC";
if (strcmp(seatclass,first)==0 || strcmp(seatclass,econ)==0 || strcmp(seatclass,eandf)==0)
{
printf("win");
}
else
{
printf("This is not a seatclass choose again");
getchar();
}
NOTE : You can use '==' to compare string in C++
The response is that the "==" operator is comparing pointers in your case you should use the strncmp function (from string.h)
"==" will point to the memory addres in case of arrays and strings in C..instead you can use strcmp function.
To compare two strings, we can use the strcmp() or strncmp() functions.
Using a strcmp() function we can compare the hole string, Using the strncmp() function we can compare the some specific range of the string.
The both functions return 0 if the string is same, else it return -1 or 1
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 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
So basically I wanted to create a program in C, in wich you would input 2 character long string (mix of letter and noumber ex.r1,u2,i3,i4,r6) to be the input in my program. Later I want to put this string in SWITCH. Is this possible?
Here's my simple sourcecode. Please correct me on any mistakes :)
#include <stdio.h>
int main(void)
{
char string[2];
scanf("%s", &string);
switch (string)
{
case 'u1' :printf("%s\n", string);break;
default :printf("ERROR");break;
}
return 0;
}
Create a code based on the string and switch on that.
#define Code(a,b) (a + 256*b)
char string[3]; // 3 not 2
if (scanf("%2s", string) != 1) { // No &
Handle_Error();
}
int scode = Code(string[0], string[1]);
switch (scode) {
case Code('u', '1') : printf("%s\n", string); break;
case Code('r', '2') : printf("r2\n"); break;
...
default :printf("ERROR");break;
}
A switch(x) needs an integer value for x and string is an array. So the original approach will not work.
The program can use an integer based on the string for x and use the same method for generating the case values. Since there is only the first 2 char of the string are of interest, the int value is unique.
No, this is not possible. Switch only works with integral types in C (int, short, long, etc, as well as types defined with enum).
You can however use a simple if-else construct to get the same behavior:
if (strcmp(string, "ui" ) == 0) //test for string equality
{
printf("%s\n", string);
}
else
{
printf("ERROR")
}
We use strcmp instead of == because we are dealing pointers which almost certainly not compare equal even when the two strings have the same content.
strcmp(str1, str2) == 0 is the standard idoim in C for comparing two strings.
strcmp returns an integer representing how two strings compare to each other. 0 means they are equal, a negative number means that the first string is lexographically "less than" the second, and a positive number means that the first string is lexographically "greater than" the second. More info can be found here.
A switch won't work here.
You need to use an if/else if construct and strcmp to compare the strings.
Also, you need at least 3 characters in your input array so that it can hold the two input characters and the terminating null character.
Of course, such a small buffer can easily overflow.
I have this code:
if (argv[i] == "-n")
{
wait = atoi(argv[i + 1]);
}
else
{
printf("bad argument '%s'\n",argv[i]);
exit(0);
}
When this code gets executed I get the following error:
bad argument '-n'
I seriously don't know why it does that. Can someone explain?
String comparisons need a function in C - usually strcmp() from <string.h>.
if (strcmp(argv[i], "-n") == 0)
{
wait = atoi(argv[i + 1]);
}
else
{
printf("bad argument '%s'\n",argv[i]);
exit(0);
}
The strcmp() function returns a negative value (not necessarily -1) if the first argument sorts before the second; a positive value (not necessarily +1) if the first arguments sorts after the second; and zero if the two values are equal.
The == operator does not work on the contents of strings because strings are effectively character pointers in this application, and the pointer get compared.
To compare the contents of strings use strcmp or strncmp.
You are comparing pointers (argv[i] and of "-n" are a char* and a const char*).
Use strcmp() instead.
What you're really doing here is pointer comparison. argv[i] is not a string, it's a pointer to a location in memory at which the actual string starts. Use strcmp().
You're comparing pointers, not string contents. argv[i] and "-n" are two different strings, stored at two different locations in memory, even if the characters inside the strings are equal.
In C, the operator == compares for equality.
Values of the same numeric type are compared the straightforward way (i.e. 2 + 2 == 4 is true).
Values of different integer (and non-integer numeric) types undergo some conversion. See elsewhere.
Pointers are equal if the point at the same address.
String literals are placed in memory not overlapping any other thing; including not overlapping anything pointed to by argv[i] (for i = 0 to argc).
So you're comparing two unequal pointers; that's why. You want to use if (!strcmp(argv[i], "-n")) { ... }.
int equal(char* stringa, char* stringb) {
while((*stringa) && (*stringb)) {
if(*stringa!=*stringb)
return FALSE;
stringa++;
stringb++;
}
return TRUE;
}
is also working for me