Skip to content Skip to sidebar Skip to footer

Is There A Function In C That Does The Same As Raw_input In Python?

Is there a C function that does the same as raw_input in Python? #in Python:: x = raw_input('Message Here:') How can I write something like that in C? Update:: I make this, but i

Solution 1:

You can write one pretty easily, but you'll want to be careful about buffer overflows:

void raw_input(char *prompt, char *buffer, size_t length)
{
    printf("%s", prompt);
    fflush(stdout);
    fgets(buffer, length, stdin)
}

Then use it like this:

char x[MAX_INPUT_LENGTH];
raw_input("Message Here:", x, sizeof x);

You may want to add some error checking, and so on.

Solution 2:

The POSIX.1-2008 standard specifies the function getline, which will dynamically (re)allocate memory to make space for a line of arbitrary length.

This has the benefit over gets of being invulnerable to overflowing a fixed buffer, and the benefit over fgets of being able to handle lines of any length, at the expense of being a potential DoS if the line length is longer than available heap space.

Prior to POSIX 2008 support, Glibc exposed this as a GNU extension as well.

char *input(const char *prompt, size_t *len) {
    char *line = NULL;
    if (prompt) {
        fputs(prompt, stdout);
        fflush(stdout);
    }
    getline(&line, len, stdin);
    return line;
}

Remember to free(line) after you're done with it.


To read into a fixed-size buffer, use fgets or scanf("%*c") or similar; this allows you to specify a maximum number of characters to scan, to prevent overflowing a fixed buffer. (There is no reason to ever use gets, it is unsafe!)

char line[1024] = "";
scanf("%1023s", line);      /* scan until whitespace or no more space */scanf("%1023[^\n]", line);  /* scan until newline or no more space */fgets(line, 1024, stdin);   /* scan including newline or no more space */

Solution 3:

Use printf to print your prompt, then use fgets to read the reply.

Solution 4:

The selected answer seems complex to me.

I think this is little easier:

#include"stdio.h"intmain(){
   char array[100];

   printf("Type here: ");
   gets(array);
   printf("You said: %s\n", array);

   return0;
}

Post a Comment for "Is There A Function In C That Does The Same As Raw_input In Python?"