I am a beginner in C programming.
I have written a program which is not functioning due to its 'OR' functionality. Here is a working code snippet:
#include <stdio.h>
#include <stdlib.h>
int main()
{
char* englishTest = 'yup';
if ( (englishTest == 'yup') || (englishTest == 'yep') || (englishTest == 'yas') || (englishTest == 'yah') )
{
printf("You may pass \n");
}
else
{
printf("You shall not pass \n");
}
return 0;
}
This is supposed to be C, not a scripting language.
There are two problems in this code:
char englishTest = 'yup';
englishTest is declared as char which in C is an integer type. It can hold only one character but you attempt to store three characters in it.
What you probably meant is:
char englishTest[] = "yup";
Please note the square brackets that denote an array (of chars). The array size can be optionally specified between the brackets. It is not specified here and the compiler uses the smallest value that can hold the string used for initialization ("yup"). This smallest value is 4: there are 3 characters in "yup" but C strings are terminated with the NULL character ('\0').
The second issue in your code is the comparison of strings. The strings are not primitive types in C. They are arrays of characters. Directly comparing two strings using the comparison operators doesn't produce the result you expect. It compares the addresses in memory where the two strings are stored, not their characters.
The C standard library provides several functions to compare two strings. The most straightforward string comparison function is strcmp(). It returns 0 if the two strings are identical, a negative value if the first string comes before the second string in the dictionary order or a negative value otherwise.
Your comparison code should be (note the C strings are enclosed in double quotes ""):
if (strcmp(englishTest, "yup") == 0 || strcmp(englishTest, "yep") == 0 ||
strcmp(englishTest, "yas") == 0 || strcmp(englishTest, "yah") == 0)
P.S. The OR operators (||) do not break anything here.
Related
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.
This question already has answers here:
scanf and strcmp with c string
(3 answers)
Closed 6 years ago.
I'm new to C and I need help.
This code doesn't work, even if I type London into the input I recieve the message from else: "Try again".
int main()
{
char capitalCity;
scanf("%s", &capitalCity);
if (capitalCity == 'London'){
printf("Is the capital city of UK.");
}
else{
printf("Try again.");
}
return 0;
}
There is no string data type in C programming language. Strings in C are represented as array of characters.
In C, char is a data type to represent a character (char in C represents the character type, suitable for storing a simple character—traditionally one from the ASCII encoding.). So, all you need to do is declare a array of char data type to represent a string in C. Each element in that array will hold a character of your string.
Also, operators in C like ==, !=, +=, + are defined for build-in data types in C and since, there is no operator overloading in C, you can't use these operators with your C-String as C-Strings are not build-in data type in C programming language.
Note: C-Strings are actually Null-terminated array of char data types. That means, last character in any C-String in C will be used to store a Null Character ('\0') which marks the end of the string.
The Header file has predefined functions that you can use to operate on C-String(Null-terminated array of char data type). You can read more about it over here.
So, your program should look like:
#define MAX_CSTR_LEN 100
int main()
{
char capitalCity[MAX_CSTR_LEN + 1]; ///An extra position to store Null Character if 100 characters are to be stored in it.
scanf("%s", capitalCity);
// Use strcmp to compare values of two strings.
// If strcmp returns zero, the strings are identical
if (strcmp(capitalCity, "London") == 0) {
printf("Is the capital city of UK.");
}
else {
printf("Try again.");
}
return 0;
}
Also, you have to use single quotes for character literals and double quotes for strings in C.
First, there are many things you need to learn. I'm trying my best to explain it to you.
In case of string as input, you can't compare by using == operator. you need to use strcmp() function which is declared in <string.h> header file, it compares character by character and return 0 if both string equal else a non-zero value.
#include <stdio.h>
#include <string.h> //for strcmp function
#define SIZE 30 //max size buffer for input
int main(){
char capitalCity[SIZE];
scanf("%s", capitalCity);
if(strcmp(capitalCity, "London") == 0){ //if(capitalCity == 'London') won't work in case of string comparison
printf("Is the capital city of UK.");
} else{
printf("Try again.");
}
return 0;
}
further reading http://www.geeksforgeeks.org/c/
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:
C Strings Comparison with Equal Sign
(5 answers)
Closed 9 years ago.
i've written some simple code as an SSCCE, I'm trying to check if string entered is equal to a string i've defined in a char pointer array, so it should point to the string and give me a result. I'm not getting any warnings or errors but I'm just not getting any result (either "true" or "false")
is there something else being scanned with the scanf? a termination symbol or something? i'm just not able to get it to print out either true or false
code:
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#define LENGTH 20
//typedef char boolean;
int main(void)
{
const char *temp[1];
temp[0] = "true\0";
temp[1] = "false\0";
char var[LENGTH];
printf("Enter either true or false.\n");
scanf("%s", var);
if(var == temp[0]) //compare contents of array
{
printf("\ntrue\n");
}
else if(var == temp[1]) //compare contents of array
{
printf("\nfalse\n");
}
}
const char *temp[1];
This defines tmp an array that can store 1 char* element.
temp[0] = "true\0";
Assigngs to the first element. This is okay.
temp[1] = "false\0";
Would assign to the second element, but temp can only store one. C doesn't check array boundaries for you.
Also not that you don't have to specify the terminating '\0' explicitly in string literals, so just "true" and "false" are sufficient.
if(var == temp[0])
This compares only the pointer values ("where the strings are stored"), not the contents. You need the strcmp() function (and read carefully, the returned value for equal strings might not be what you expect it to be).
Use strcmp for comparing strings:
#include <stdio.h>
int main(void)
{
const int LENGTH = 20;
char str[LENGTH];
printf("Type \"true\" or \"false\:\n");
if (scanf("%19s", str) != 1) {
printf("scanf failed.");
return -1;
}
if(strcmp(str, "true") == 0) {
printf("\"true\" has been typed.\n");
}
else if(strcmp(str, "false") == 0) {
printf("\"false\" has been typed.\n");
}
return 0;
}
and also note that:
string literals automatically contain null-terminating character ("true", not "true\0")
const int LENGTH is better than #define LENGTH since type safety comes with it
"%19s" ensures that no more than 19 characters (+ \0) will be stored in str
typedef char boolean; is not a good idea
unlikely, but still: scanf doesn't have to succeed
and there is no #include <iostream> in c :)
== checks for equality. Let's see what you're comparing.
The variable var is declared as a character array, so the expression var is really equivalent to &var[0] (the address of the first character in the var array).
Similarly, temp[0] is equivalent to &temp[0][0] (the address of the first character in the temp[0] array).
These addresses are obviously different (otherwise writing var would automatically write temp[0] as well), so == will always return 0 for your case.
strcmp, on the other hand, does not check for equality of its inputs, but for character-by-character equality of the arrays pointed to by its inputs (that is, it compares their members, not their addresses) and so you can use that for strings in C. It's worth noting that strcmp returns 0 (false) if the strings are equal.
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.