1

I'd like to be able to compare a character on stdin with a characters of my specification. The purpose of this is to filter out every other input as wrong, while maintaining only the specified single chars as commands. Like on stdin "nn" or "qddaw" -> wrong go again but "n" make something useful.

Here is what I have in mind "code-wise":

if (input does not contain 'c' or 's' or 'q' or 'n') { 
    printf("some kind of error");
}

Well I tried to create an array with specified characters like array[] = {'a', 'b', 'c'} so I could be able to compare it with a string on the stdin with function strncmp.. like

char c[256];
scanf("%s", c)
if (strncmp(array, c, 1) != 0) printf("error");

but it doesn't seem to work. Any suggestions?

Edit1: Here is actual piece of code:

char c[256];
char* s = "nsrld";
char* quiter = "q";

do 
    {
        printf(">");
        scanf("%s", c);
        if (only when there is no 'n' or 's' or other char from char* s on input)
        {
            errorHandle(ERROR_WRONG_CMD);
        }
        scanf("%*[^\n]"); scanf("%*c");
    } while (strcmp(c,quiter) != 0);

as you can see I handled the 'q' thing quite well, but multiple chars are pain in the ass. Thanks for any advice.

Edit 2: or in other words I need a function which will compare input with a set of given characters and only if there is one OR another (like 'q' or 's' the function will pass (but not if there are characters together like 'qs')

Mathew Thompson
  • 55,877
  • 15
  • 127
  • 148
Markus
  • 686
  • 1
  • 11
  • 18
  • With getchar(), did you try printing out `c`? Print it out like this: printf("c = %c / %d\n", c, c); Also, what is the type of `c`, `char` or `int`? – George Skoptsov Apr 14 '12 at 22:55
  • @GeorgeSkoptsov I edited the post because I actually need to distinguish input "qdqqdq" from "q" in which case only standalone "q" will do the work and any other input will report an error.. – Markus Apr 15 '12 at 11:57

8 Answers8

1
char c = getchar();
switch (c) {
case 'c':
case 's':
case 'q':
case 'n':
  do_something();
  break;
default:
  print_error();
};

The above code should work. I don't know why your if statement wasn't working. Generally a switch works well in this type of scenario too.

keelerjr12
  • 1,693
  • 2
  • 19
  • 35
  • the problem here is with getchar as it takes only one char so input like "cawwffawf" will pass this test. What I need is when input is like "caawfaw" printf error but when input is exactly one character "c" do something useful. – Markus Apr 15 '12 at 08:12
1
int ch = getchar();
if (ch != EOF)
{
    if (strchr("csqn", ch) == NULL)
    {
        printf("Evil Bad Character <%c> in Hex %02X\n", ch, ch);
    }
    else
    {
        /* Do stuff with ch */
    }
}
else
{
    printf("EOF on input\n");
}
EvilTeach
  • 28,120
  • 21
  • 85
  • 141
  • I have edited the first post to reflect my needs. I need to be able to distinguish input "cwdwdaf" from 'c' in which case only 'c' will make something useful any other input will parse an error. – Markus Apr 15 '12 at 08:43
  • Your question and examples are misleading. getchar gets one character at a time. If you want to deal with checking all of the input, then performing some action, you need to rework your question. – EvilTeach Apr 15 '12 at 12:44
  • yeah sorry for the confusion, I have already figured it out, thank you for your time and effort, I really appreciate it! :) – Markus Apr 15 '12 at 12:57
1

I didn't make myself clear enough. What I need is input "type what ever you want" like "wwqwqe" and do the error unless the input is just 'c' or just 's' (and a few more).

char usersInput[200] = "";            /* A buffer to hold the input values */
char *result = gets(usersInput);      /* Fill the buffer from stdin */
if (result != NULL)                   /* If we got something */
{
    if (strlen(usersInput) == 1)      /* the input must be exactly 1 character */
    {
        char ch = usersInput[0];
        if (strchr(ch, "csqn") == NULL)    /* It must be a valid values */
        {
            printf("Evil Bad Character <%c>\n", ch);
        }
        else
        {
            /* Do stuff with the known valid input value ch */
        }
    }
    else
    {
        puts("The input value must be exactly 1 character\n");
        puts("and must be 'c', 's', 'q' or 'n'");
    }
}
else
{
    puts("EOF or ERROR while reading stdin\n");
}

This should do the job.

One warning. gets is not smart enough to know that usersInput is 200 characters long.

It will gleefully let you type in 201 characters or more, which overwrites other characters in memory. That sort of thing can lead to hard-to-find bugs.

EvilTeach
  • 28,120
  • 21
  • 85
  • 141
  • hmm and if I want to have the infinite loop as on my example [link](http://stackoverflow.com/a/10162127/1333847) and I want to return error after hitting "enter" twice .. what do I do? in my version I can hit enter as many times as I want and nothing happens, it's still waiting for another input.. – Markus Apr 15 '12 at 13:24
0

Write a function

int IsGood(int c)
{
    if(c=='a'||c=='b'||c=='c')
    return 1;
    else
    return 0;
}
BenMorel
  • 34,448
  • 50
  • 182
  • 322
Anil
  • 578
  • 4
  • 12
  • I have edited the first post to reflect my needs. I need to be able to distinguish input "cwdwdaf" from 'c' in which case only 'c' will make something useful any other input will parse an error. – Markus Apr 15 '12 at 08:43
0

Your first solution should work. If that's the exact same code you posted - then your problem might because the printf needs a newline at the end to flush to console.

hide0
  • 394
  • 1
  • 2
  • 13
0

I have thought the string as sets... So if the intersection of them is the void set then we will fail -> printf("Error")... otherwise the output is none...

#include <stdio.h>
#include <string.h>

int intersection(char* source, char* search)
{
  int i,j;
  for(i = 0; i < strlen(search); i++)
    if(strchr(source,search[i]))j++;
  if(j != strlen(search))return 0;
  else return 1;
}

int main()
{
  char *letters = "eo";
  char *p = "hello";
  int e = intersection(p,letters);
  if(e==1)puts("Non Void");  
  else puts("Void");
}
  • thank you for this code, but maybe I didn't make myself clear enough. What I need is input "type what ever you want" like "wwqwqe" and do the error unless the input is just 'c' or just 's' (and a few more). With your code, if I will specify p as set of "cs" even input like "cs" will pass. The code 'q' ends the prog. `char c[256]; char* s = "nsrld"; char* quiter = "q"; do { printf(">"); scanf("%s", c); if (dunno) { errorHandle(ERROR_WRONG_CMD); } scanf("%*[^\n]"); scanf("%*c"); } while (strcmp(c,quiter) != 0);` – Markus Apr 15 '12 at 08:24
0

This worked for me:

    char c[256];
    char* s = "nqsrld";
    char* quiter = "q";

    do 
    {
        printf(">");
        scanf("%s", c);
        if ((strpbrk(s, c) == 0) || (strlen(c) >= 2))
        {
            errorHandle(ERROR_WRONG_CMD);
        }
        scanf("%*[^\n]"); scanf("%*c");
    } while (strcmp(c,quiter) != 0);

Thanks to everyone for their help.

Swati
  • 50,291
  • 4
  • 36
  • 53
Markus
  • 686
  • 1
  • 11
  • 18
0

While it looks as if you've got a solution, it might be worth mentioning that what you're asking for doesn't sound as if it's all that far away from the standard 'getopt' functionality... See http://www.gnu.org/software/libc/manual/html_node/Getopt.html for example.

Gwyn Evans
  • 1,361
  • 7
  • 17