How to compare with If the value of two strings? - c

I want to compare the two strings and show the amount of wins for each player. I do not quite understand how the string.h library works, but in searches I've shown that it should work for this comparison
#include <stdio.h>
#include <string.h>
int main()
{
printf("Player 1: ");
scanf("%s", &play1);
printf("Player 2: ");
scanf("%s", &play2);
printf("Total matches: ");
scanf("%d", &t_matches);
for (i = 1; i <= t_matches; i++) {
printf("Winner match %d: ", i);
scanf("%s", &win1);
if (strcmp(win1, play1)) {
p1++;
} else if(strcmp (win1, play2)) {
p2++;
}
}
printf("%s win %d matches\n", play1, p1);
printf("%s win %d matches\n", play2, p2);
}

The strcmp function returns 0 if the strings are equal. You're checking if they are unequal. You instead want:
if (strcmp(win1, play1) == 0) {
p1++;
} else if(strcmp (win1, play2) == 0) {
p2++;
}

Related

if condition is not functioning properly

i tried to make a calculator but could the compiler is checking my if conditions properly.
here is my code,
i could not figure out how to solve this
#include <stdio.h>
#include <stdlib.h>
int main()
{
int first;
int sec;
char mode;
printf("enter your forst number : ");
scanf("%d",&first);
printf("enter your second number : ");
scanf("%d",&sec);
printf("to add press \"a\" \n");
printf("to subtract press \"s\" \n");
printf("to multiply press \"m\" \n");
printf("to divide press \"d\" \n");
printf("so, what do you wanna do ");
scanf(" %c",&mode);
printf("%d %d %s \n",first,sec,mode);
if (mode == 'a')
{
printf("%d \n",first + sec);
}
else if (mode == "s")
{
printf("%d \n",first-sec);
}
else if (mode == "m")
{
printf("%d \n",first*sec);
}
else if (mode == "d")
{
printf("%d \n",first/sec);
}
else
{
printf("enter a valid operation code \n");
}
return 0;
}
void def(char name[],int age)
{
printf("het ur a %s and yo age is %i \n",name,age);
}
first attempt tried using a string instead of character (failed )
second attempt tried using a character but failed though!!
For comparing a single character in c, you must use single quotes. Consider an array of characters array[4] = {'c','a','r','\0'};
if(array[0] == 'c'){
//...
}
Comparing with double quotes, make the value inside it a string. For comparing strings you should #include <strings.h> and use the strcmp function.
There are two problems
mode == "s" mode is a char so just use mode == 's' and do the same for others also.
printf("%d %d %s \n",first,sec,mode); should be printf("%d %d %c \n",first,sec,mode);
you are using %s for printing a char
In your code "s" is a string not a caracter,to get a caracter you should write like this: 's'
here is the correction of your code :
int main()
{
int first;
int sec;
char mode;
printf("enter your forst number : ");
scanf("%d",&first);
printf("enter your second number : ");
scanf("%d",&sec);
printf("\nMenu : \n");
printf("\nto add press \"a\" \n");
printf("to subtract press \"s\" \n");
printf("to multiply press \"m\" \n");
printf("to divide press \"d\" \n");
printf("so, what do you wanna do ");
scanf(" %c", &mode);
printf("%d %d %c \n",first,sec,mode);
if(mode == 'a')
{
printf("%d \n",first + sec);
}
else if (mode == 's')
{
printf("%d \n",first-sec);
}
else if (mode == 'm')
{
printf("%d \n",first*sec);
}
else if (mode == 'd')
{
printf("%d \n",first/sec);
}
else
{
printf("enter a valid operation code \n");
}
return 0;
}

Hangman game - C

Im doing a hangman game as a school project but Im facing an issue:
do{
system("cls");
// Header of the game
printf("\n HANGMAN GAME\n\n\n");
// Present letters found
for (i=0; word[i]!='\0'; i++)
printf (" %c ", word_2[i]);
printf("\n");
// Present positions to the letters
for (i=0; word[i]!='\0'; i++)
printf("___ ");
printf("\n");
// ****PLAYER'S ANSWERS*****
// Read player's answers
printf("\n\n Whats your guess + <enter>: ");
scanf("%c", &letter);
scanf("%c", &c);
// Verify if the letter is in the word
found=0;
for(i=0; word[i]!='\0'; i++)
if (word[i] == letter){
word_2[i] = letter;
corrects++;
max_attemps--;
found = 1;
printf("\nWell done, %s. You have now %d attempts\n\n", name, max_attemps);
system("pause");
}
if(found == 0){
max_attemps--;
printf("\nOh no, %s. You have now %d attempts\n\n", name, max_attemps);
system("pause");
}
if (max_attemps <= 0 || corrects == lenght) {
end = 1;
}
} while (end == 0);
When I got a right letter that have two or more position in the word it takes from me two or more attempts because of the system("pause") when in fact just had to takes me one. But if I don't put the system("pause") the board will be cleared before I can see the message. Anyone knows what can I do to solve this? I'll be very grateful.
Check your found flag only after you have scanned the whole word:
// Verify if the letter is in the word
found=0;
for(i=0; word[i]!='\0'; i++)
if (word[i] == letter){
word_2[i] = letter;
corrects++;
max_attemps--;
found = 1;
// comment out
// printf("\nWell done, %s. You have now %d attempts\n\n", name, max_attemps);
// system("pause");
}
if(found == 1)
{
printf("\nWell done, %s. You have now %d attempts\n\n", name, max_attemps);
system("pause");
}
else{
max_attemps--;
printf("\nOh no, %s. You have now %d attempts\n\n", name, max_attemps);
system("pause");
}
if (max_attemps <= 0 || corrects == lenght) {
end = 1;
}

Running into a segfault when referencing pointer

I'm taking an intro to C programming course, and I'm trying to understand pointers, and how exactly they work. I tried to pass just the variable counter through gameRuntime();, but counter wasn't being returned towards after the while loop. So, I opted to use a pointer. And now I'm in a bigger mess than I started.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int *gameRuntime(int *counter)
{
srand(time(NULL));
int random = rand() % 100 + 1;
printf("> %d <\n", random);
int guess;
*counter = 1;
int local_counter = (*counter);
while ((guess != random) && (local_counter <= 10))
{
printf("\n-----------------------\n");
printf("What is your guess?\n-----------------------\n> ");
scanf("%d", &guess);
if ((guess > 100) || (guess < 1))
{
printf("Please choose a number between 1 and 100\n");
}
else if (guess < random)
{
printf("My number is larger than %d!\n", guess);
local_counter++;
printf("%d guesses left!\n", (11 - local_counter));
}
else if (guess > random)
{
printf("My number is less than %d!\n", guess);
local_counter++;
printf("%d guesses left!\n", (11 - local_counter));
}
else if (guess == random)
{
printf("You guessed it! My number was %d!\n", random);
printf("You found it with just %d guess(es)!\n", local_counter);
}
}
(*counter) = local_counter;
return counter;
}
int main()
{
char quit;
int counter;
int random;
printf("Welcome to the Number Guess Game!\n");
printf("I chose a number between 1 and 100 and you have only 10 chances to guess it!\n\n");
printf("Continue? [Y\\N]\n\n> ");
scanf("%c", &quit);
if ((quit == 'n') || (quit == 'N'))
{
printf("Exiting....");
return 0;
}
else
{
printf("\n=*=+=*=+=*=+=*==*=+=*=+=*=+=*==*=+=*=+=*=+=*==*=+=*=+=+*\n");
printf(" ~ ~ ~ Ready? ~ ~ ~ \n");
printf("=*=+=*=+=*=+=*=+=*=+=*=+=*=+=*=+=*=+=*=+=*=+=*=+=*=+=*=+=*\n");
printf("\n");
printf("\n-----------------------");
printf("\nOk, I've made up my mind!\n");
printf("-----------------------\n");
}
gameRuntime(counter);
printf("\n---%d---\n", counter);
char continueGame;
while ((continueGame != 'N') || (continueGame != 'n'))
{
printf("\n---%d---\n", counter);
if (counter >= 10)
{
printf("SORRY! You could not find my number with 10 guesses!\n");
printf("My number was %d\n", random);
printf("Maybe next time!\n");
printf("\nTry again? [Y\\N]\n");
scanf(" %c", &continueGame);
if ((continueGame == 'Y') || (continueGame == 'y'))
{
gameRuntime(counter);
}
else
{
printf("Thanks for playing! See you later!");
return 0;
}
}
else
{
printf("Play again? [Y\\N]\n> ");
scanf(" %c", &continueGame);
if ((continueGame == 'Y') || (continueGame == 'y'))
{
gameRuntime(counter);
}
else
{
printf("\nThanks for playing! See you later!");
return 0;
}
}
}
}
Any help would be much appreciated, TIA
Change
gameRuntime(counter);
to
gameRuntime(&counter);
You are passing the value of counter, and then you used it like if it was the address of something (you dereferenced the pointer). It does compile because pointers and ints are interchangeable in c, but that doesn't mean that the behavior is defined. It should however, generate a warning about pointer to int conversion. You can also, convert all warnings to errors to prevent compilation in case of a warning.
Warnings can be ignored in very rare cases, so as a rule of thumb make your compiler warn about everything it can and if possible, let it treat warnings as errors.
By applying the suggested fix, you pass the address of counter, which is a pointer holding the location of counter in memory, thus you can then affect the value at that location by dereferencing the pointer.

how to check if user input is a certain character

I am trying to check if the user inputs y or something else.
I have tried creating a string and looping through what the user inputs, but that doesn't work.
char answer[] = "n";
for(int i = 0; i < sizeof(answer)/4; i++) {
if(answer[i] == "y") {
calculatorPrompt();
} else if(answer[i] === "n") {
printf("Okay, bye!");
System(100);
}
}
This is my code (I'm sure it crashes on the if statement):
printf("Thanks for that\nDo you want a calculator?(y/n)");
char answer = 'n';
scanf("%s", answer);
if(answer == 'y') {
calculatorPrompt();
} else if(answer == 'n') {
printf("Okay bye!");
Sleep(100); //wait for 100 milliseconds
}
calculatorPrompt() function:
void calculatorPrompt() {
int a = 0;
int b = 0;
int sum = 0;
printf("Enter your first number: ");
if(scanf("%d\n", a) != 1) {
checkNumber();
} else {
printf("Enter your second number: ");
if(scanf("%d\n", b) != 1) {
checkNumber();
} else {
sum = calculate(a, b);
printf("Your answer is: %d", sum);
}
}
}
calculate() function:
int calculate(int a, int b) {
return a + b;
}
checkNumber() function:
void checkNumber() {
printf("Really? You didn't enter a number... Now exiting..");
return;
}
I have included <windows.h> <stdio.h> and <stdbool.h>
I'm also confused as to why it crashes.
The return value of the program is -1,073,741,819.
You have multiple issues with scanf() statements in the code :
in calculatorPrompt() funtion of your code, you use :
if(scanf("%d\n", a) != 1) //wrong : sending variable as argument
This is wrong because you need to send address of the variable as the argument not the variable itself as argument.
if(scanf("%d", &a) != 1) //correct : sending address as argument
similarly change while scanning other integers in the code.
here,
char answer = 'n';
scanf("%s", answer);
As you are using the wrong format specifier, this invokes Undefined behavior.
here since answer is a char so, instead use :
scanf(" %c", &answer); //space to avoid white spaces
and as I've already suggested in the comments :
You use i < sizeof(answer)/4 in the for loop
No! it must be i < sizeof(answer), as in a string every element occupies only 1 byte not 4 (you are mistaking it for an int array)
by the way you don't have any strings in your code
I don't recommend the code you have written for calculator, yet wanted to help you find the working code. Try following code that is based on your own code. Hope you'll see the differences and understand the reasons why the program was crashing in your case.
#include <Windows.h>
#include <stdio.h>
#include <stdbool.h>
bool checkNumber(int num)
{
return true;
}
int calculate(int a, int b) {
return a + b;
}
void calculatorPrompt() {
int a = 0;
int b = 0;
int sum = 0;
printf("Enter your first number: ");
scanf_s("%d", &a);
if (checkNumber(a)) {
}
printf("Enter your second number: ");
scanf_s("%d", &b);
if (checkNumber(b)) {
}
sum = calculate(a, b);
printf("Your answer is: %d", sum);
}
int main()
{
printf("Thanks for that\nDo you want a calculator?(y/n)");
char answer = 'n';
scanf_s("%c", &answer);
if (answer == 'y') {
calculatorPrompt();
}
else if (answer == 'n') {
printf("Okay bye!");
Sleep(100); //wait for 100 milliseconds
}
}
#include <windows.h>
#include <stdio.h>
#include <stdbool.h>
void calculatorPrompt(void);
int main(void){
printf("Thanks for that\nDo you want a calculator?(y/n)");
char answer = 'n';
scanf("%c", &answer);//scanf need address of store place
if(answer == 'y') {
calculatorPrompt();
} else if(answer == 'n') {
printf("Okay bye!\n");
Sleep(100); //wait for 100 milliseconds
}
return 0;
}
void checkNumber(void);
int calculate(int a, int b);
void calculatorPrompt() {
int a = 0;
int b = 0;
int sum = 0;
printf("Enter your first number: ");
if(scanf("%d", &a) != 1) {//\n : skip white spaces and wait input not spaces
checkNumber();//call when invalid input
} else {
printf("Enter your second number: ");
if(scanf("%d", &b) != 1) {
checkNumber();
} else {
sum = calculate(a, b);
printf("Your answer is: %d\n", sum);
}
}
}
void checkNumber(void){//output message and clear input.
fprintf(stderr, "invalid input!\n");
scanf("%*[^\n]%*c");//clear upto end of line.
}
int calculate(int a, int b) {
return a + b;
}
When you scan a character , you just need to use %c. If you are planning to continue with string you must use strcmp() for comparison not ==.

C language - strcmp returns 0 always and strcpy not copying the string in another array

I want to run this code where I enter two strings and user put the option for performing the following task.
After I enter 'a' in the menu, the statement strcpy(s_1,s_2); the string is copied to s_1 but when I added
#include <string.h>
it asked me to use strcpy_s() which I did and code stopped working.
When I enter 'b' in the menu, I get only one output
Both Strings are equal to each other
I don't understand why strcmp() returns 0 always.
It would be great if someone help me out in this issue.
By the way I'm using Visual Studio 2015 for compiling my C code.
#include< stdio.h>
#include< string.h>
#include< stdlib.h>
#include< process.h>
//USER-DEFINED FUNCTIONS
char top_down();
char copy_function();
char compare_function();
//char adder_function();
void header(void);
#define MAX 1000
void header()
{
printf("*-*-*-*-*TASK_PERFORMER*-*-*-*-*");
printf("\n\n");
}
//PROGRAM STARTS HERE
main()
{
//VARIABLE DECLARATION
char x =
{ 0 };
//HEADING FUNCTION
header();
//USER-DEFINED FUNCTION CONSISTING OF ALL INPUTS.
top_down();
//TERMINAL-PAUSE
system("pause");
}
char top_down()
{
char s1[MAX] =
{ 0 }, s2[MAX] =
{ 0 }, x =
{ 0 };
printf("Enter the First String : \n");
fgets(s1, MAX, stdin);
printf("\n");
printf("The Entered First String : \n");
printf("%s", s1);
printf("\n");
printf("Enter the Second String : \n");
fgets(s2, MAX, stdin);
printf("\n");
printf("The Entered Second String : \n");
printf("%s", s2);
printf("\n");
printf("*-*-*-TYPE ANY OPTION TO PERFORM TASK-*-*-*");
printf("\n");
//GIVEN OPTIONS FOR SELECTOR
printf("Enter one option from the following : \n\n");
printf("(a) To Copy one string to another. \n");
printf("(b) To Compare two string. \n");
printf("(c) To Add a string to the end of another string. \n");
printf("\n");
repeat:
printf("Enter Your Option : \n");
scanf_s("%c", &x);
printf("\n");
//OPTION-SELECTOR
switch (x)
{
case 'a':
copy_function(s1, s2);
break;
case 'b':
compare_function(s1, s1);
break;
case 'c':
//adder_function(s1, s2);
break;
default:
printf("INVALID OPTION \n");
printf("Please Try Again \n");
goto repeat;
break;
return;
}
}
char copy_function(char s_1[], char s_2[])
{
int x = 0;
x = strlen(s_2);
printf("Second String will be copied to First string now \n");
//strcpy(s_1, s_2);
strcpy_s(s_1, x, s_2);
printf("\n");
printf("First String Output : \n");
printf("%s", s_1);
return;
}
char compare_function(char s_1[], char s_2[])
{
int a = 0, l1 = 0, l2 = 0, i = 0;
printf("First String will be compared to Second String now \n ");
//printf("\n");
if (strcmp(s_1, s_2) == 0)
printf("Both String are equal to each other \n");
else if (strcmp(s_1, s_2) > 0)
printf("First String is greater than Second String");
else
printf("First String is lesser than Second String \n");
return;
}
Not sure if your program is in progress. I modified it and removed anything I thought was not necessary.
The functions' signatures change to void
Removed x in main
Return type of main set to int (It is int by default, but this spares you the warning of the compiler)
I work on Linux, so I removed the system(...), feel free to add it.
Only left variables declarations in top_down (not important, but an initial value should have a meaning and in your case there is no meaning to 0)
Changed scanf_s("%c", &x); to scanf(" %c", &x); (note the space. not sure if on windows that makes a difference. please check.)
Changed the function call compare_function(s1, s1); to compare_function(s1, s2);
Removed the return statements in the void functions
In copy_function I removed int x = 0; and x = strlen(s_2);
In copy_function I changed strcpy_s(s_1, x, s_2); to strcpy(s_1, s_2);
In compare_function I removed int a = 0, l1 = 0, l2 = 0, i = 0;
You use label/goto. That's ok, but considered not cool nowadays. You could use a loop and break in case of an invalid option.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
//USER-DEFINED FUNCTIONS
void top_down();
void copy_function();
void compare_function();
//char adder_function();
void header(void);
#define MAX 1000
void header() {
printf("*-*-*-*-*TASK_PERFORMER*-*-*-*-*");
printf("\n\n");
}
//PROGRAM STARTS HERE
int main() {
//HEADING FUNCTION
header();
//USER-DEFINED FUNCTION CONSISTING OF ALL INPUTS.
top_down();
return 0;
}
void top_down() {
char s1[MAX], s2[MAX], x;
printf("Enter the First String : \n");
fgets(s1, MAX, stdin);
printf("\n");
printf("The Entered First String : \n");
printf("%s", s1);
printf("\n");
printf("Enter the Second String : \n");
fgets(s2, MAX, stdin);
printf("\n");
printf("The Entered Second String : \n");
printf("%s", s2);
printf("\n");
printf("*-*-*-TYPE ANY OPTION TO PERFORM TASK-*-*-*");
printf("\n");
//GIVEN OPTIONS FOR SELECTOR
printf("Enter one option from the following : \n\n");
printf("(a) To Copy one string to another. \n");
printf("(b) To Compare two string. \n");
printf("(c) To Add a string to the end of another string. \n");
printf("\n");
repeat:
printf("Enter Your Option : \n");
scanf(" %c", &x);
printf("\n");
//OPTION-SELECTOR
switch (x) {
case 'a':
copy_function(s1, s2);
break;
case 'b':
compare_function(s1, s2);
break;
case 'c':
//adder_function(s1, s2);
break;
default:
printf("INVALID OPTION \n");
printf("Please Try Again \n");
goto repeat;
break;
}
}
void copy_function(char s_1[], char s_2[]) {
printf("Second String will be copied to First string now \n");
strcpy(s_1, s_2);
printf("\n");
printf("First String Output : \n");
printf("%s", s_1);
}
void compare_function(char s_1[], char s_2[]) {
printf("First String will be compared to Second String now \n ");
if (strcmp(s_1, s_2) == 0)
printf("Both String are equal to each other \n");
else if (strcmp(s_1, s_2) > 0)
printf("First String is greater than Second String");
else
printf("First String is lesser than Second String \n");
}

Resources