-3

I want to take an input in C language but it should be without the use of scanf function. So how can it be done?

1 Answers1

2

fgets is almost always the best choice for reading input from the command line:

#define BUFFER_SIZE 100
...
char buffer[BUFFER_SIZE];
fgets(buffer, BUFFER_SIZE, stdin);
buffer[strcspn(buffer, "\n")] = '\0'; // See https://stackoverflow.com/questions/2693776/removing-trailing-newline-character-from-fgets-input/27729970

From here, you can use string parsing functions on buffer, such as sscanf, strtol, strtoul, strtod, strtof, strstr, strchr, etc. to parse the string.

One of the main advantages of taking input this way is it gives you greater control over how you populate your program's data with it. For example, if you want to populate a comma-delimited list of integers of unknown length, scanf does not give you this level of control:

char buffer[BUFFER_SIZE];
size_t cCommas = 0, i;
char *pNext = &buffer[0], *pStop = NULL;
long *longs = NULL;
fgets(buffer, BUFFER_SIZE, stdin);
buffer[strcspn(buffer, "\n")] = '\0';

while (pNext = strchr(pNext, ','))
{
    cCommas++;
    pNext++;
}

longs = malloc((cCommas + 1) * sizeof(long));
if (NULL == longs)
{
    perror("malloc");
    exit(EXIT_FAILURE);
}

i = 0;
pNext = buffer;
do
{
    longs[i] = strtol(pNext, &pStop, 10);
    pNext = (pStop + 1);
    i++;
}
while (i <= cCommas);

use(longs);

free(longs);
longs = NULL;
Govind Parmar
  • 20,656
  • 7
  • 53
  • 85