Hello,
Im new to coding sorry,
The problem is that if I enter a string greater than the specified LENGTH, in the switch case function leads to the default which should not. But a few exercises before it was said to use it that way until I added a few new cases to the switch case function.
I write the expected output in new message due to limits.
Code:
`#include<stdio.h>
#define LENGTH 20
void readChar(char string[], int length);
void printP(char string[]);
void printA(char string[], int length);
int findChar(char string[],char a[]);
int main(void) {
char String0[LENGTH]="";
char String1[LENGTH]="";
char a[1]="";
do {
printf("What is the command? ");
readChar(String0, LENGTH);
switch (String0[0]) {
case 'q':
printf("End!!!\n");
break;
case 'p':
printf("The current string is:");
printP(String1);
break;
case 'a':
printA(String1, LENGTH);
break;
case 'e':
printf("String? ");
readChar(String1, LENGTH);
break;
case 'f':
printf("Which character are you looking for? ");
readChar(a, 1);
int k=findChar(String1, a);
printf("The index when '%c' first appears is %d \n",a[0],k);
break;
default:
printf("This is unknown! '%c'\n", String0[0]);
break;
}
} while (String0[0] != 'q');
return 0;
}
void readChar(char string[], int length) {
int i;
for (i = 0; i <length; i++) {
char c;
c = getchar();
if (c == '\n') {
string[i] = '\0';
break;
}
else {
string[i] = c;
}
}
}
void printP(char string[]) {
for (int i = 0; string[i] != '\0'; i++) {
if (string[i] == '\n') {
putchar('\n');
} else {
putchar(string[i]);
}
}
putchar('\n');
}
void printA(char string[], int length) {
printf("The current array is: [");
for (int i = 0; i < length; i++) {
if (string[i] == '\0') {
printf("\0");
} else if (string[i] == '\n') {
printf("\n");
} else {
printf("%c", string[i]);
}
if (i != length - 1) {
printf(", ");
}
}
printf("]\n");
}
int findChar(char string[],char a[]){
int i;
for(i=0;i<LENGTH;i++){
if(string[i]==a[0]){
return (i);
break;
}
else
continue;
}
if(i==LENGTH)
return -1;
}`