C 语言用户输入
用户输入
您已经了解到 printf() 用于在 C 中输出值。
要获取 用户输入,可以使用 scanf() 函数:
实例
输出用户输入的数字:
#include <stdio.h>int main() {// Create an integer variable that will store the number we get from the userint myNum;// Ask the user to type a numberprintf("Type a number and press enter: \n");// Get and save the number the user typesscanf("%d", &myNum);// Print the number the user typedprintf("Your number is: %d", myNum);return 0;}
scanf() 函数有两个参数:变量的格式说明符(%d,在上面的实例中)和引用运算符(&myNum),后者存储变量的内存地址。提示:在下一章中,您将学习有关 内存地址 和 函数 的更多内容。
用户输入字符串
您还可以获取用户输入的字符串:
实例
输出用户的名称:
#include <stdio.h>int main() {// Create a stringchar firstName[30];// Ask the user to input some textprintf("Enter your first name: \n");// Get and save the textscanf("%s", firstName);// Output the textprintf("Hello %s.", firstName);return 0;}
注意,您必须指定字符串/数组的大小(我们使用了一个非常高的数字,30,但至少我们可以确定它将为 firstname 存储足够的字符),并且在
scanf() 中处理字符串时,您不必指定引用运算符(&)。