[QUOTE=Siersan]Using strchr it would look something like this.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int check(char str[], int search);
int main(void)
{
char buf[BUFSIZ];
int ch;
printf("Enter a string: ");
fflush(stdout);
if (fgets(buf, sizeof buf, stdin) == NULL)
return EXIT_FAILURE;
printf("Enter a character to search for: ");
fflush(stdout);
if ((ch = getchar()) == EOF)
return EXIT_FAILURE;
if (check(buf, ch))
printf("%c was found\n", ch);
else
printf("%c was not found\n", ch);
return EXIT_SUCCESS;
}
int check(char str[], int search)
{
return strchr(str, search) != NULL;
}
Just a friendly note:
fgets() will append a \n to the string, if you then just press enter at the character search prompt you will find the \n. The answer will be: was found
vegaseat
DaniWeb's Hypocrite
5,989 posts since Oct 2004
Reputation Points: 1,345
Solved Threads: 1,417
>if you then just press enter at the character search prompt you will find the \n.
That's reasonable (and expected) behavior. Let's say you want to test for exceptionally long lines:
while (fgets(buffer, sizeof buffer, stdin) != NULL && !check(buffer, '\n')) {
/* Append buffer to a dynamic string */
}
If you don't want to find the newline, then remove it before the test, or verify the value of the search character as being neither EOF nor '\n'.
Narue
Bad Cop
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
>if you then just press enter at the character search prompt you will find the \n.
That's reasonable (and expected) behavior.
No argument with that! It's the result telling me that an invisible character was found that can be confusing to the user.
vegaseat
DaniWeb's Hypocrite
5,989 posts since Oct 2004
Reputation Points: 1,345
Solved Threads: 1,417