C 中是否有一个函数与 Python 中的 raw_input 功能相同?
是否存在与 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;
}
错误是程序运行并打印消息,并通过 scanf 获取用户类型,但随后它挂起并退出..? ?
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.. ??
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以很容易地编写一个,但您需要小心缓冲区溢出:
然后像这样使用它:
您可能需要添加一些错误检查,等等。
You can write one pretty easily, but you'll want to be careful about buffer overflows:
Then use it like this:
You may want to add some error checking, and so on.
POSIX.1-2008 标准指定了函数getline,它将动态(重新)分配内存,为任意长度的行腾出空间。
与 gets 相比,它的优点是不会溢出固定缓冲区,而与 fgets 相比,它的优点是能够处理任意长度的行,但代价是成为如果行长度长于可用堆空间,则可能存在 DoS。
在 POSIX 2008 支持之前,Glibc 也将其公开为 GNU 扩展。
完成后请记住
free(line)
。要读入固定大小的缓冲区,请使用
fgets
或scanf("%*c")
或类似方法;这允许您指定要扫描的最大字符数,以防止固定缓冲区溢出。 (没有理由使用gets
,它是不安全的!)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 overfgets
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.
Remember to
free(line)
after you're done with it.To read into a fixed-size buffer, use
fgets
orscanf("%*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 usegets
, it is unsafe!)使用
printf
打印提示,然后使用fgets
来读取回复。Use
printf
to print your prompt, then usefgets
to read the reply.所选答案对我来说似乎很复杂。
我认为这更容易一些:
The selected answer seems complex to me.
I think this is little easier: