[英]Making the input function of Python into C
在我用於程序構建的沙箱中有一個名為<cs50.h>
庫。 它具有獲取特定數據類型的輸入函數,格式為get_(data type)
。
所以我嘗試在 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;
}
它有效,但唯一的問題是它只能接受字符串,而且我不知道如何獲取要使用的變量。 那么如何獲得所需的數據類型呢?
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);
}
也就是說,為什么要麻煩,當您可以使用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.