Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/285.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
将Python的输入函数转换成C语言_Python_C_Input_Cs50 - Fatal编程技术网

将Python的输入函数转换成C语言

将Python的输入函数转换成C语言,python,c,input,cs50,Python,C,Input,Cs50,在我用于程序构建的沙箱中有一个名为的库。它具有获取特定数据类型的输入函数,其中的格式为get_389;(数据类型) 因此,我尝试在Python中试验一个get_int()函数: def get_int(text): result = int(input(text)) return result 而且它有效!因此,我尝试用C编写Python的输入函数: #include <stdio.h> #include <cs50.h> char *input(ch

在我用于程序构建的沙箱中有一个名为
的库。它具有获取特定数据类型的输入函数,其中的格式为
get_389;(数据类型)

因此,我尝试在Python中试验一个
get_int()
函数:

def get_int(text):
    result = int(input(text))
    return result
而且它有效!因此,我尝试用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;
}
#包括
#包括
字符*输入(字符*文本);
int main(){
char*name=input(“你叫什么名字?”);
printf(“你好,%s.\n”,名称);
}
字符*输入(字符*文本){
printf(“%s”,文本);
char*result=get_字符串(“”);
返回结果;
}

它可以工作,但唯一的问题是它只能接受字符串,我不知道如何获取要使用的变量。那么如何获得所需的数据类型呢?

C中将字符串转换为整数的等效函数是,from
stdlib.h

#include <stdlib.h>

int get_int(char *text);

...

int get_int(char *text) {
    char *input_str = input(text);
    return atoi(input_str);
}

scanf()
对我来说有点棘手,尤其是它获取输入的方式。我没有说我想要一个
get_int()
函数,但好吧,我想这可以帮助我理解数据类型交换是如何工作的。
scanf()
指针本身不再可怕时,就不再可怕了。您只需告诉它您想要什么,并将输入的位置交给它(
&result
,一个指向内存区域的指针,以便它用输入覆盖)。在这种情况下,您甚至不必担心分配或释放内存,因为C是按值返回的。
#include <stdio.h>

int get_int(char *text);

...

int get_int(char *text) {
    printf("%s", text);
    int result;
    scanf("%d", &result);
    return result;
}