是否有不一样在Python raw_input C函数?

#in Python::
x = raw_input("Message Here:")

我怎么能写的东西一样,在C?

<强>更新::

我做这个,但我得到一个错误:

#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;
}

和所述错误是,程序运行并打印MSG和由scanf的采取什么样的用户类型,但随后挂起并退出..?

有帮助吗?

解决方案

您可以编写一个很容易,但对缓冲区溢出你要小心:

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

然后,使用这样的:

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

您可能需要添加一些错误检查,等等。

其他提示

POSIX.1-2008 标准规定了功能的函数getline ,该将动态(重新)分配存储器来腾出空间的线的任意长度。

这具有超过的是无懈可击的溢出的固定缓冲器gets的权益,并在的能够处理任意长度的线中,在作为一个潜在的DoS牺牲fgets惠若线长度比可用堆长空间。

此前POSIX 2008支持,Glibc的暴露此作为GNU扩展为好。

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

你用它做了以后记得free(line)


要读入一个固定大小的缓冲器,使用fgetsscanf("%*c")或相似的;这允许您指定的字符的最大数量进行扫描,以防止溢出一个固定的缓冲区。 (没有理由永远使用gets,它是不安全的!)

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

使用printf打印您的提示,然后使用 fgets 阅读的答复。

在所选答案似乎复杂我。

我觉得这是更容易一些:

#include "stdio.h"

int main()
{
   char array[100];

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

   return 0;
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top