0

This might be a rookie question, but I need to make sure that the input given by the user is of data type char [%c] or a string [%s].

If it were an integer, I would just do something like this:

    int data, x;
    do {
      printf("Please enter a number: ");
      x = scanf(" %d", &data);
      getchar();
    } while(x!=1);

So I was wondering if there's a similar way to do this, if the input is supposed to be a string or a character. Thanks, Any help would be appreciated!

  • Its better to check with [ASCII](http://www.asciitable.com/) value – IrAM Dec 14 '20 at 04:18
  • Provide some sample inputs, to receive better answers – IrAM Dec 14 '20 at 04:24
  • 2
    Unless your hit EOF or some actual stream error, character and/or string input will *always* succeed. It can literally be *anything*, so unless you're going to specify considerably stricter semantics and precise protocol for what you mean, there is no realistic answer to your question. – WhozCraig Dec 14 '20 at 04:30
  • @WhozCraig It's for an assignment and i have to somehow make sure the user types in an alphabet. I've done this with an integer before, but i have no idea where to start from when it comes to char or a string. – dean_winchester Dec 14 '20 at 04:35
  • @IrAM I would provide some sample inputs, but I'm still trying to figure out where to start from.. – dean_winchester Dec 14 '20 at 04:37
  • So... the restriction isn't just "string" or "character", it's *alphabetic* ? That's what I'm talking about: precise requirements. So, non-alphabetic characters (punctuation, control characters, whitespace, etc) are off the menu. Just a..z and A..Z. ? What about 0..9 ? – WhozCraig Dec 14 '20 at 04:40
  • @WhozCraig Yes, exactly. The input has to be the alphabets from A to Z and the lower case letters should work as well. 0.. 9 shouldn't! Apologies for not making it clear earlier. – dean_winchester Dec 14 '20 at 04:45

2 Answers2

1

Avoid to use %c in scanf() because some unexpected character like \r\n will be input.

You can use a char[2] to receive a single character. An \0 will be filled after your string to represent the end of string, so the length of array must be bigger than 1.

An example:

#include <stdio.h>

int main()
{
    char data[2];

    scanf("%1s", data);

    if (data[0] >= 'a' && data[0] <= 'z') // custom your constraint here
    {
        // legal
        printf("legal: %s", data);
    }
    else
    {
        // illegal
        printf("illegal: %s", data);
    }

    return 0;
}

While I input b, the data will be "b\0".

DCTewi
  • 120
  • 1
  • 8
  • 1
    Consider a width limit `scanf("%1s", data);` so code behaves well enough even when input is more than 1. – chux - Reinstate Monica Dec 14 '20 at 06:50
  • Do not use `data[0] >= 'a' && data[0] <= 'z'` to test for letters. It is not guaranteed to work by the C standard. Use `isalpha` to test for a letter and, if desired, `islower` to test for lowercase. They are declared in ``. – Eric Postpischil Dec 14 '20 at 09:54
0

part of the answer is if you just want to read only alphabet you can use below.

#include <stdio.h>
#include <ctype.h>

int main()
{
    char ch;
    do {
        printf("enter a char:");
        scanf(" %c",&ch);
    }while(!isalpha(ch));
    printf("%c",ch);
    return 0;
}

Update 1:

Just for the completeness and for the FUN part of the programing, have added code here.

This works well (not tested robustly, you can do if you need to) for the single char input or for a string of length 9.

Remember to type the EOF after input is entered in case length of input is < 9.

and read EOF behavior on same line and new line.

#include <stdio.h>
#include <ctype.h>

#define LEN 10

int main()
{
    char ch;
    char str[LEN] = {0};
    int i = 0;
    int ret;
    printf("enter a char or string(len = 9) and press EOF if len < 9\n");
    do {
        if(1== (ret = scanf(" %c",&ch)))
        {
            if(isalpha(ch))
                str[i++] = ch;
        }                
        else
            printf("scanf:Error (%d)\n", ret);
    }while(ret != EOF && ( !isalpha(ch) || i < LEN-1));
    str[i] = '\0';
    printf("str is %s\n",str);
    return 0;
}
IrAM
  • 1,720
  • 5
  • 18
  • The naked `scanf` (i.e. never checking the result to ensure you actually read a character) will irritate more than its fair share of engineers, even if the odd professor doesn't know/care any better. Regardless, this is at least a step in the right direction. – WhozCraig Dec 14 '20 at 04:49
  • Thank You! As far as I know isalpha() wouldn't work with a string though, would it? – dean_winchester Dec 14 '20 at 04:55
  • @dean_winchester added code to read the strings, it is just for FUN, you can use it if you need the same behavior. – IrAM Dec 14 '20 at 07:23