-1

I have to check if a character(string) contains a scanned letter.

char password[15]="STACKOVERFLOW";
char check;
printf("Type in a letter to check if it is in the password/n");
scanf("%c", check);

Now I want to check if the check is in the password and print true or false.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • 1
    [strchr](http://www.cplusplus.com/reference/cstring/strchr/) is what you are looking for, in this case `if (strchr(password, c)) printf("%c is in password\n", c);` – David Ranieri Dec 14 '20 at 19:31
  • 5
    Does this answer your question? [How do I check if a string contains a certain character?](https://stackoverflow.com/questions/58146750/how-do-i-check-if-a-string-contains-a-certain-character) – ATP Dec 14 '20 at 19:32
  • Can I also use strchr to check if there is a number in a string? – Juhász Koppány Dec 14 '20 at 19:34
  • @JuhászKoppány do you mean a digit? in this case [strspn](http://www.cplusplus.com/reference/cstring/strspn/) is a better option. – David Ranieri Dec 14 '20 at 19:38

1 Answers1

1

For starters use

scanf(" %c", check);
       ^^^^

instead of

scanf("%c", check);

to skip white space characters from the input stream.

To check whether a character is present in a string use the standard function strchr declared in the header <string.h>. For example

#include <string.h>

//...


if ( strchr( password, check ) == NULL ) // if ( !strchr( password, check ) )
{
    puts( "The character is absent" );
}

Or

if ( strchr( password, check ) ) 
{
    puts( "Bingo! The character is present" );
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335