scanf("%c", &findChar);
reads the next character pending in the input stream. This character will be the newline entered by the user that stopped the previous conversion, so findChar
will be set to the value '\n'
, without waiting for any user input and printf
will output this newline without any other visible effect.
Modify the call as scanf(" %c", &findChar)
to ignore pending white space and get the next character from the user, or more reliably write a loop to read the read and ignore of the input line.
Note also that scanf("%[^\n]s", userIn);
is incorrect:
scanf()
may store bytes beyond the end of userIn
if the user types more than 29 bytes of input.
- the
s
after the ]
is a bug, the conversion format for character classes is not a variation of the %s
conversion.
Other problems:
void
is not a proper type for the return value of the main()
function.
- the
<stdio.h>
header is required for this code.
Here is a modified version:
#include <stdio.h>
int main() {
char userIn[30];
int c;
char findChar;
int i, found;
printf("Please enter a string: ");
if (scanf("%29[^\n]", userIn) != 1) {
fprintf(stderr, "Input failure\n");
return 1;
}
/* read and ignore the rest of input line */
while ((c = getchar()) != EOF && c != '\n')
continue;
printf("Please enter a character to search for: ");
if (scanf("%c", &findChar) != 1) {
fprintf(stderr, "Input failure\n");
return 1;
}
printf("Searching for '%c'\n", findChar);
found = 0;
for (i = 0; userIn[i] != '\0'; i++) {
if (userIn[i] == findChar) {
found++;
printf("found '%c' at offset %d\n", c, i);
}
}
if (!found) {
printf("character '%c' not found\n", c);
}
return 0;
}