I am trying to get multiple words input and multiple lines into one array. But somewhere the code skips getting the input and skips to end the program. I have tried adding space before and after the ' %s' (or '%s ') but it won't work (maybe because it's inside a loop?). Would really appreciate anyone's help! It also starts to act weird if I enter more than two-three words :( My goal is to find how many times a specific letter has occurred throughout all those words and lines.
#include <stdio.h> //include standard library
int main(){
int lineCount, occuranceCount;
printf("How many lines are you going to enter?");
scanf("%d", &lineCount);
char input[lineCount][100], searchChar;
for(int i=0; i<lineCount; i++){
printf("Please enter line #%d (100 characters of less):",i+1);
scanf("%s", &input[i]);
}
printf("What letter do you want to check the frequence in those lines? ");
scanf("%c", &searchChar);
for(int j=0; j<lineCount; j++){
for(int k=0; k<100; k++){
if(input[j][k] != '\0'){
if(input[j][k]==searchChar)
occuranceCount++;
}
}
}
printf("The letter occurs for %d time", occuranceCount);
return 0;
}
fgets(or POSIXgetline) are recommended for user input instead ofscanfwhich is full of pitfalls for the unwary... Regardless which input function you use, you must validate the return to have any confidence you will not invoke Undefined Behavior on your next attempt to access what you attempted to read.scanf("%s", &input[i]);->scanf("%99s", input[i]);scanf ("%d"...)which leaves the'\n'(from the user pressing Enter instdin. (2) you callscanf ("%s"...)which reads nothing because the"%s"format specifier reads from the beginning up to the first whitepace ('\n'being whitespace) which is not removed fromstdin; (3) you callscanf ("%c"...)which happily accepts the'\n'as a character for its input and (4) you fail to check the return of all of the calls.