I'm a first year student so I'm still struggling with C language.
One of the assignments want's me to make a program where user inputs a word then a letter which the program will use to find all of the letters positions in that word (lets say he enters 'world' and 'r' so the script prints out 'r positions are in 3' / or for 'worldr' 'r positions are in 3 and 6' / or for 'worldrr' 'r positions are in 3 6 and 7').
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char word[20];
printf("Enter a word: ");
scanf("%s", word);
char letter;
printf("Enter a letter: ");
scanf(" %c", letter);
for(int i = 0; i < strlen(word); i++){
if(word[i] == letter){
printf(" %c positions are in %d", letter, i+1);
}
}
}
ALSO the program skips "scanf(" %c", letter);
" part (error but nothing in logs) if I write %c without the space in the beginning "scanf("%c", letter);
" like so. Why?
Basically If I write if(word[i] == 'r'){
instead of if(word[i] == letter){
it works just fine but It won't work like I need it to.
I've searched for a solution but no luck other than to try strchr
but I need it to print out the array position not the actual memory ram position or something like that or maybe I just don't quite get it yet since I haven't used it before ever. If so I would greatly appreciate If someone could explain me how to solve my problem using if(word[i] == letter){
and strchr
ways. I'd love to understand both.
Thank you in advanced!