views:

171

answers:

3

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 get an error ::

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

typedef char * string;

int raw_input(string msg);
string s;
string *d;

main(){
raw_input("Hello, Enter Your Name: ");
d = &s;
printf("Your Name Is: %s", s);

}

int raw_input(string msg){
string name;
printf("%s", msg);
scanf("%s", &name);
*d = name;
return 0;
}

and the error is that program run and print the msg, and take what user type by scanf, but then it hangs and exit.. ??

+5  A: 

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.

Carl Norum
fflush(stdout); what this mean ??
Rami Jarrar
@Rami, a lot of `printf()` implementions don't actually flush the output until a newline character. If you want the prompt to be on the same line, you have to force the system to flush the output.
Carl Norum
A: 

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

Turtle
+1  A: 

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 */
ephemient
Care to explain your bland assertion that fgets is unsafe?It is not perfect, but unless you pass the wrong parameters I would hardly say it is *unsafe*.
Turtle
Oh. Obviously I was thinking of `gets`. `fgets` has a length parameter and thus is not vulnerable in the same way. I'll fix that up.
ephemient