I have a really weird bug. If I write a name which contains more than 4 characters, the printf will only output the first 4 characters.
Important note: I am not allowed to use any other library than stdio.h and I am not allowed to use anything else than scanf for input and printf for output. Moreover I am not allowed to modify the paramater list of the functions and I have to use const char. The code runs on putty via ssh on a unix system.
My code and the input/output are below. In addition, the while loop has a bug too ._.
#include <stdio.h>
int searchCharacters(const char*, char);
int getLength(const char*);
int main() {
char yesNo;
int end = 0;
const char name[] = {""};
printf("please enter a name: ");
scanf("%s", name);
int length = getLength(name);
printf("\n%s has a length of %i", name, length);
fflush(stdin);
while(end != 1) {
printf("\n\nWould you like to search a character in %s (y / n)?", name);
scanf(" %c", &yesNo);
switch(yesNo) {
case 'y':
printf("\nPlease enter a character: ");
char searchingCharacter;
scanf("%c", &searchingCharacter);
int numberOfCharacters = searchCharacter(name, searchingCharacter);
printf("\nThe letter %c is %i-times", searchingCharacter, numberOfCharacters);
break;
case 'n':
printf("\nGood bye!");
end++;
break;
}
}
return 0;
}
int searchCharacter(const char s[], char c) {
int numberOfIterations = getLength(s);
int numberOfCharacters = 0;
int i;
for (int i = 0; i < numberOfIterations; i++) {
if (s[i] == c) {
numberOfCharacters++;
}
}
return numberOfCharacters;
}
int getLength(const char s[]) {
int i = 0;
while(s[i++]);
return (i - 1);
}
Input/Output:
please enter a name: abcdefg
abcd has a length of 7 characters.
Would you like to search a character in abcd (y / n)? y
<-------------- AUTOMATIC/BUG WHILE LOOP --------------------------->
Please enter a character:
The letter
is 0-times.
</--------------AUTOMATIC/BUG WHILE LOOP---------------------------->
Would you like to search a character in abcd (y / n)? n
Good bye!
scanf("%c", &yesNo);
-->scanf(" %c", &yesNo);
– kiran Biradarconst char name[] = {""}; printf("please enter a name: "); scanf("%s", name);
were it not for the fact that name is const and hence should not be modified at all. I would start with fixing these bugs first and then worry about the program not working as expected. – Tanveer Badar