[英]Making the input function of Python into C
There is this library called <cs50.h>
in a sandbox I use for program building.在我用于程序构建的沙箱中有一个名为<cs50.h>
库。 It has input functions to get a certain data type, where the format would be get_(data type)
.它具有获取特定数据类型的输入函数,格式为get_(data type)
。
So I tried experimenting a get_int()
function in Python:所以我尝试在 Python 中试验get_int()
函数:
def get_int(text):
result = int(input(text))
return result
And it works!它有效! So I tried to experiment the input function of Python by writing it in C:于是我试着用C写来试验一下Python的输入函数:
#include <stdio.h>
#include <cs50.h>
char *input(char *text);
int main() {
char *name = input("What's your name? ");
printf("Hello, %s.\n", name);
}
char *input(char *text) {
printf("%s", text);
char *result = get_string("");
return result;
}
It works, though the only problem is that it can only take strings, and I don't know how to get which variable to be used.它有效,但唯一的问题是它只能接受字符串,而且我不知道如何获取要使用的变量。 So how do I get the needed data type?那么如何获得所需的数据类型呢?
The equivalent function in C that converts a string into an integer is atoi()
, from stdlib.h
: C 中将字符串转换为整数的等效函数是atoi()
,来自stdlib.h
:
#include <stdlib.h>
int get_int(char *text);
...
int get_int(char *text) {
char *input_str = input(text);
return atoi(input_str);
}
That said, why bother, when you could just use scanf()
from stdio.h
, which is as flexible for input as printf()
is for output, and more flexible than python's input()
in general?也就是说,为什么要麻烦,当您可以使用stdio.h
scanf()
时,它对于输入与printf()
用于输出一样灵活,并且通常比 python 的input()
更灵活?
#include <stdio.h>
int get_int(char *text);
...
int get_int(char *text) {
printf("%s", text);
int result;
scanf("%d", &result);
return result;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.