How do I compare two strings in if statement in C [duplicate] - c

This question already has answers here:
How do I properly compare strings in C?
(10 answers)
Closed 2 years ago.
I'm pretty new to C; I usually code in C++ before my lecturer told me to code it in C. So how do I compare two strings in if statement in C?
#include <stdio.h>
char name[100],tanya[50],type[100];
int value;
int main()
{
printf("Enter name: ");
scanf("%s", name);
printf("Hello %s", name);
printf( ", Are you interested in Anime? (y/n)");
scanf("%s", tanya);
if (tanya == "y") { // this is the part
printf("Wow, you're an interesting person %s");
do {
} while ();
} else {
printf("good day sir.");
}
return 0;
}

if (tanya == "y")
You do not need to use nor compare strings, when you only want to input a single character like y or n.
Instead use a char object, input a character in it and compare if this character matches y or Y inside the condition of the if statement:
printf(", Are you interested in Anime? (y/n)");
char tanya;
scanf("%c", &tanya);
if (tanya == 'y' || tanya == 'Y')
{....}
If you explicitly want to use strings, you need to compare two strings properly.
In C, one common way to compare two strings is by using the strcmp() function in the header string.h.
In your code it can be used as:
if(strcmp(tanya,"yes") == 0);
to accomplish the comparison and the proof of the if statement to check if both strings are equal.
The whole code shall be like this:
#include <stdio.h>
#include <string.h>
char name[100],tanya[50],type[100];
int value;
int main()
{
printf("Enter name: ");
scanf("%s", name);
printf("Hello %s", name);
printf( ", Are you interested in Anime? (y/n)");
scanf("%s", tanya);
if(strcmp(tanya,"yes") == 0){
printf("Wow, you're an interesting person %s", tanya);
}
else{
printf("Good day sir.");
}
return 0;
}
By the way, it is kind of superficial to kick anybody just because he/she ainĀ“t like animes ;-)

To compare strings in c, you can use strcmp() provided in string.h library.
char a[10],b[10];
if( strcmp(a,b) == 0 ) {
// .. both are identical
}
this function returns 0 or non zero, you'll get details in the ref.
alternatively, while learning, implement your own compare function, like:
#include <stdio.h>
#include <string.h>
bool isEqual(char* a, char* b) {
char* c = a, *d = b;
while(*c != '\0' && *d != '\0') {
if(*c != *d) return false;
c++;
d++;
}
return true;
}
int main() {
char a[10],b[10];
strcpy(a,"name");
strcpy(b,"name");
if(isEqual(a,b)) {
printf("%s %s are same\n",a,b);
}else{
printf("%s %s are not same\n",a,b);
}
return 0;
}
This might help you to think about what's going on under the hood.

Related

Why isn't my code working in C on VS Code?

Pls check it out and help meeee I'm stuck at it since 2+ hours (the "score" variable and other variables that you might see aren't mentioned here because my original code is too long, so I've just listed the important parts of it):
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main() {
while (1) { //using 1 as a condition since "true" doesn't work
char* low(char* question) { // a function used for converting the user input into all lowercased
for (int i = 0; question[i]; i++) {
question[i] = tolower(question[i]);
}
}
printf("1. Is Python a programming language or a creature? ");
char question[25];
scanf("%s", &question);
low(question);
if (strcmp(question, "programming language") == 0 || (strcmp(question, "creature") == 0)) {
printf("Correct! It's both actually 1+ ");
score += 1;
break;
} else {
printf("Invalid Input ");
continue;
}
}
}
Problem: It keeps printing out Invalid input even if the answer is correct
Instead of this:
scanf("%s", &question);
This:
scanf("%s", question);
Reason: question is an array, so when it gets passed as a function parameter, it becomes a pointer to the first element in the array - which is where scanf needs to write to.

Error : Wrong comparison between pointer and integer

My code seems fine, but I get this warning (warning: comparison between pointer and integer), what is the best solution to solve this problem?
I have already used double notation marks for (char exit = "E"), also used the same thing with while but the same problem.
#include <stdio.h>
int main()
{
char c[1];
char exit = 'E';
while (c != exit)
{
printf("Enter a character\n\n");
scanf("%s", c);
printf("your character is : %s\n-------------------\n", c);
}
}
#include <stdio.h>
int main()
{
char c[1];
char exit = 'E';
while (c != exit) // here ...
{
printf("Enter a character\n\n");
scanf("%s", c);
printf("your character is : %s\n-------------------\n", c);
}
}
you are trying to compare a char to the pointer the array c decays to. What you perhaps wanted to do is to compare the first character of the array to the character exit:
while (c[0] != exit)
But that still doesn't make much sense since c is uninitialized and the user not yet had a chance to make any input. Better use a do ... while-loop:
#include <stdio.h>
int main()
{
char c[1];
char exit = 'E';
do {
printf("Enter a character\n\n");
scanf("%s", c);
printf("your character is : %s\n-------------------\n", c);
} while (c[0] != exit);
}
Next thing is, that scanf("%s", c); could fail (yes unlikely, but possible). And the user could enter more characters than there is room for in the array c. You should never use scanf() whithout checking the return value nor "%s" without specifying a WIDTH for the conversion specifier to limit the characters put into the array.
When reading a string you need memory for WIDTH characters + a terminating '\0'. So if you want to read a string of one character, the array has to have at least 2 elements:
#include <stdlib.h
#include <stdio.h>
int main()
{
char c[2];
char exit = 'E';
do {
printf("Enter a character\n\n");
while (scanf("%1s", c) != 1 ) {
fputs("Input error!\n");
return EXIT_FAILURE;
}
printf("your character is : %s\n-------------------\n", c);
} while (c[0] != exit);
}
But if you only want to read one character you are better off with getchar():
#include <stdio.h>
{
int ch;
while (printf("Enter a character\n\n"),
(ch = getchar()) != EOF && ch != 'E')
{
printf("your character is: %c\n-------------------\n", (char) ch);
}
}
i believe this is what you are trying to do.
warning is because you have not initialzed your character and also you were comparing address of character to character value.
#include <stdio.h>
int main()
{
char c[1];
char exit = 'E';
while ((c[0]=getchar()) != exit)
{
if(c[0]==EOF)break;
printf("your character is : %c\n",c[0]) ;
}
printf("ended");
}

How can I verify if one string variable is equal to a specific string that is not a variable in a do while in C language?? (not compare two strings)

I have already read the C string function man pages. The best thing I found was "strcmp" and "strncmp". But that's not what I want because it compares two strings. I just want to compare one like this...
char input[3];
do {
//important code
printf ("You want to continue??);
fflush(stdin);
gets(input);
} while (input == "yes" || "Yes);
It doesn't work. I would need to not use string and just a char like: "y" for yes. Is there a way I can do what I want? How can I compare just this one string with these values?
If you want to make string comparison, use strcmp. You will compare just one variable, as you want it, but with two different values. Change line :
while (input == "yes" || "Yes");
to :
while ( strcmp(input,"yes") == 0 || strcmp(input, "Yes") == 0);
Also, change :
char input[3];
to :
char input[4];
as you need to take into account the terminating \0 character.
Here I wrote a simple solution for what you're trying to achieve.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char input[4];
do {
printf ("You want to continue??");
fflush(stdin);
gets(input);
} while (strcmp(input, "yes") == 0 || strcmp(input, "Yes") == 0);
return 0;
}
Most likely you are going run into newline character that gets carried over
to next input. Here is a solution for that.
#include <stdio.h>
#include <stdlib.h>
int
main(void)
{
char input[4], garbage[50];
do
{
//important code
printf ("You want to continue??");
scanf("%s", input);
fgets(garbage, sizeof(garbage), stdin); //Newline char is now stored into garbage.
} while (strcmp(input,"yes") == 0 || strcmp(input,"Yes") == 0 );
return 0;
}

Anagram problems

I'm new to this forum and would like to seek help. I'm trying to modify an anagram program based on code from http://www.sanfoundry.com/c-program-...ings-anagrams/.
This time, however, I have used array pointers to obtain input from the user. I have also created a function "check_input" to ensure that the input consists of ONLY characters and excludes symbols(!, #, $). However, when I ran the program, it still accepts those symbols and does not break like I wanted it to. Please help.
Plus, I intend to make the program treat upper-case letters the same way as lower-case letters. Can this be achieved by using the "stricmp" function? If so, where should I place that function? Alternative methods are also appreciated.
Update: Sorry. I've added the check_input code at the bottom.
#include <stdio.h>
#include <ctype.h>
#include <string.h>
int test_anagram(char *ptrArray1, char *ptrArray2);
int check_input(char array1[], char array2[]);
int main()
{
char array1[100], array2[100];
char *pArray1, *pArray2;
int flag;
pArray1 = array1;
pArray2 = array2;
printf("Enter the first word: \n");
gets(pArray1);
printf("Enter the second word: \n");
gets(pArray2);
check_input(pArray1, pArray2);
flag = test_anagram(pArray1, pArray2);
if(flag == 1){
printf("\"%s\" and \"%s\" are anagrams.\n", pArray1, pArray2);
}else{
printf("\"%s\" and \"%s\" are not anagrams.\n", pArray1, pArray2);
}
return 0;
}
int test_anagram(char array1[], char array2[])
{
int num1[26] = {0}, num2[26] = {0}, i = 0;
while(array1[i] != '\0')
{
num1[array1[i] - 'a']++;
i++;
}
i = 0;
while(array2[i] != '\0')
{
num2[array2[i] - 'a']++;
i++;
}
for(i=0;i<26;i++)
{
if(num1[i] != num2[i]){
return 0;
}
return 1;
}
}
int check_input(char array1[], char array2[])
{
while(isalpha((int)array1) != 1){
break;
}
while(isalpha((int)array2) != 1){
break;
}
}
You haven't (yet) posted the full code of the check_input() function but one advice would be to validate the input when the user inputs every character.
You can do this using f.e. the getchar() function and checking if the inputted character is a letter, as well as converting it to the lowercase (or uppercase if you will).
You can do lowercase convertion like this:
#include <ctype.h>
// ...
tolower('A');

Program crashing, can't explain why?

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
int compare(char word[], char mystery[])
{
int i=0;int bool=1;
while((i<=20)&&(bool==1))
{
if (word[i]==mystery[i])
i++;
else
bool=0;
}
return bool;
}
char readCharacter()
{
char character = 0;
character = getchar();
character = toupper(character);
while (getchar() != '\n') ;
return character;
}
void readString(char *word,char *mystery)
{
int i=0;
printf("Enter the word to guess : ");
scanf("%s",word);
while(*((word)+(i)) != '\0')
{
*((word)+(i))= toupper(*(word+i));
*((mystery)+(i))='*';
i++;
}
*(mystery+i)='\0';
}
void process(char *word,char *mystery,char letter,int *change)
{
int i=0;
while (*((word)+(i))!= '\0')
{
if (*((word)+(i))==letter)
{
*((mystery)+(i))=letter;
*change=1;
}
i++;
}
}
void test(char *word,char *mystery, int triesleft)
{
if (*mystery!=*word)
{
printf("The mystery word is : %s",*mystery);
printf("\n You have %d tries left.", triesleft);
}
else
{
printf("You won !");
}
}
int main()
{
int triesleft = 10; int change=0;
char word[20]; char mystery[20];char letter;
readString(&word,&mystery);
while((compare(word,mystery)==0) && (triesleft>0))
{
change=0;
printf("Enter the letter :");
letter=readCharacter();
process(&word,&mystery,letter,&change);
if ((change)==1)
triesleft--;
test(&word,&mystery,triesleft);
}
if (triesleft>0)
return 0;
printf("You lost.");
return 1;
}
I'm a beginner in C and I wanted to code a simple Hangman game in C and it compiled fine but it seems to crash after entering the first letter and I can't find a solution !
I don't know what may be the cause but I had a lot of trouble using strings in C, as they don't exist maybe it was a bad manipulation of that I don't know :/
You first call to readString is enough to crash the program.
word and mystery are arrays, so &word is a char ** not a char *. You should use
readString(word, mystery);
But compiler should have issue a warning on that. Warning are not there to distract beginners to to denote possible (probable if you do not understand the warning) mistakes.
There are probably other problems later ...
In the readString() function, you should use '\0' instead of NULL, as C strings are ended with this character.
You cannot declare a variable named bool as it is a type. In C, it is not actually defined for all compilers as bool is not part of the standard but some compilers and some platform will define it anyway

Resources