Program crashing, can't explain why? - c

#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

Related

Program is getting crashed when using getch and getche

#include <stdio.h>
#include <conio.h>
#define max 100
void compare(char *name,char* input);
int main()
{
int i=0;
char name[max]="santosh";
char input[max];
printf("enter the password\n");
while((input[i]=getchar())!='\n'){
i++;
}
input[i]='\0';
compare(name,input);
return 0;
}
void compare(char *name,char* input){
while((*name==*input)&&(*name!='\0'&&*input != '\0')){
*name++;
*input++;
}
if(*name=='\0'&&*input=='\0')
printf("Correct Password");
else
printf("Incorrect Password");
}
This Program is getting crashed in vs code but when I use getchar() instead of getch() or getche() all is working fine.
Why it is not working with getch() and how it will run as I want user to insert a password and thus want to use getch() not getchar().
First of all #define max generates a warning "macro redefinition", so change that.
The second problem is that getch() and getche do not convert the Enter key to 'newline' \n but to 'return' \r
The third problem is that instead of incrementing the pointers, you are incrementing what they point to.
Here is the corrected code:
#include <stdio.h>
#include <conio.h>
#define MAXX 100 // fixed macro name collision
void compare(char *name, char* input);
int main(void) // corrected definition
{
int i = 0;
char name[MAXX] = "santosh";
char input[MAXX];
printf("enter the password\n");
while((input[i] = getche()) != '\r') { // fixed '\n' check
i++;
}
input[i] = '\0';
compare(name, input);
return 0;
}
void compare(char *name,char* input){
while(*name == *input && *name != '\0' && *input != '\0') {
name++; // fixed pointer increment
input++; // fixed pointer increment
}
if(*name == '\0' && *input == '\0')
printf("Correct Password\n");
else
printf("Incorrect Password\n");
}
Finally you should also check i does not exceed the array bounds. The strings seem long enough, but not for players who try to break the program.

Why is the value of my strcmp not equal to 0 or invalid?

I am still new to programming and there are a lot of things I still don't know but I'd like to ask why my if statement doesn't seem to be working properly. It seems the value
of strcmp(bookName, tolower(searchedName)) when the variable searchedName = "introduction to c" is not 0.
Why is this?
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main() {
char bookName[30] = "introduction to c programming";
char searchedName[30];
printf("Enter the book you are searching for: ");
scanf("%s", &searchedName);
if (strcmp(bookName, tolower(searchedName)) != 0) {
printf("The book is not in elibrary");
} else {
printf("The book is in elibrary");
}
return 0;
}
tolower() is for converting characters, not strings. You will have to apply it to each characters in the string separately.
You don't need & before arrays in this case because arrays in expressions are automatically converted to pointers (except for some case).
%s in scanf() will stop at whitespace character. %[^\n] is useful to read until hitting a newline character.
Try this:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main() {
char bookName[30] = "introduction to c programming";
char searchedName[30];
char searchedName_lower[30];
int i;
printf("Enter the book you are searching for: ");
scanf("%[^\n]", searchedName);
i = 0;
do {
searchedName_lower[i] = tolower((unsigned char)searchedName[i]);
} while (searchedName[i++] != '\0');
if (strcmp(bookName, searchedName_lower) != 0) {
printf("The book is not in elibrary");
} else {
printf("The book is in elibrary");
}
return 0;
}

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");
}

Print a string till a particular character comes

I want the string to be printed till character ('e') comes.
Code which I tried:-
#include <stdio.h>
int main() {
int a,i,x;
char b[10];
char ch;
//enter input string
for(i=0;i<10;i++)
scanf("%c",&b[i]);
for(i=0;i<10;i++)
if(b[i]!='e')
printf("%c",b[i]);
return 0;
}
Input:abcdefghij
Actual output:abcdfghij
Desired output:abcd
Question : Where am I wrong ? Will putting a break inside if block work here?
This is much cleaner if you want to use scanf.
#include <stdio.h>
int main()
{
char b[101];
scanf("%100s", b);
printf("%s\n", b);
return(0);
}
Or even better.
#include <stdio.h>
#define MAX_LENGTH 100
int main()
{
char b[MAX_LENGTH+1]; // add 1 for the terminating zero
scanf("%100s", b);
printf("%s\n", b);
return(0);
}
This one uses fgets to read the entire line.
#include <stdio.h>
#define MAX_LENGTH 100
int main()
{
char b[MAX_LENGTH];
fgets(b, MAX_LENGTH, stdin);
printf("%s", b);
return(0);
}
How to print a string till limit?
What code should do is use fgets().
Avoid using scanf(). Is is too easy to use wrong.
#include <stdio.h>
#include <string.h>
int main() {
char b[100];
if (fgets(b, sizeof b, stdin)) {
// If code needs to lop off the potential \n at the end
b[strcspn(b, "\n")] = '\0';
printf("%s\n", b);
}
return 0;
}
Advanced issues include how to handle excessively long input lines and error handling - not shown here.
Here is what you need to do
#include <stdio.h>
int main()
{
int a,i,x;
char b[10];
char ch;
//enter input string
for(i=0;i<10;i++)
{
scanf("%c",&b[i]);
}
for(i=0;i<10;i++)
{
if(b[i]=='e')
{
break;
}
}
return 0;
}
re
There are several mistakes!
If you are initializing your loops from 0 then you need to set the condition till i<100.
Change your format specifiers to %s.
Change your IF statement to if(b[i]!='\0').
#include <stdio.h>
int main()
{
int i;
char b[10];
for(i=0;i<10;i++)
{
scanf("%c",&b[i]);
}
for(i=0;i<10;i++)
{
if(b[i]=='e')
{
break;
}
printf("%c",b[i]);
}
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');

Resources