Is there a function in C that does the same as raw_input in Python?

天大地大妈咪最大 提交于 2021-01-27 06:38:02

问题


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.. ??


回答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.




回答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 */



回答3:


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




回答4:


The selected answer seems complex to me.

I think this is little easier:

#include "stdio.h"

int main()
{
   char array[100];

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

   return 0;
}


来源:https://stackoverflow.com/questions/2496857/is-there-a-function-in-c-that-does-the-same-as-raw-input-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!