简体   繁体   中英

Making the input function of Python into C

There is this library called <cs50.h> in a sandbox I use for program building. It has input functions to get a certain data type, where the format would be get_(data type) .

So I tried experimenting a get_int() function in Python:

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:

#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 :

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

#include <stdio.h>

int get_int(char *text);

...

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM