Cprogramming 简明教程
C - User Input
Need for User Input in C
每个计算机应用程序都从用户那里接受某些数据,对这些数据执行预定义的处理以生成输出。C 中没有可以读取用户输入的关键字。
Every computer application accepts certain data from the user, performs a predefined process on the same to produce the output. There are no keywords in C that can read user inputs.
与 C 编译器捆绑在一起的标准库包括 stdio.h header file ,其库函数 scanf() 最常用于 accept user input from the standard input stream 。此外, stdio.h 库还提供其他用于接受输入的函数。
The standard library that is bundled with the C compiler includes stdio.h header file, whose library function scanf() is most commonly used to accept user input from the standard input stream. In addition, the stdio.h library also provides other functions for accepting input.
Example
为了了解用户输入的必要性,请考虑以下 C 程序 −
To understand the need for user input, consider the following C program −
#include <stdio.h>
int main(){
int price, qty, ttl;
price = 100;
qty = 5;
ttl = price*qty;
printf("Total: %d", ttl);
return 0;
}
上面的程序通过将购买的商品价格和数量相乘来计算总购买金额。运行该代码并检查其输出 −
The above program calculates the total purchase amount by multiplying the price and quantity of an item purchased by a customer. Run the code and check its output −
Total: 500
对于价格和数量具有不同值的另一笔交易,你需要编辑程序,输入值,然后再次编译并运行。每次都这样做是一项繁琐的任务。相反,必须在运行程序后提供将值分配给变量的规定。 scanf() 函数在运行时读取用户输入,并将值分配给一个变量。
For another transaction with different values of price and quantity, you need to edit the program, put the values, then compile and run again. To do this every time is a tedious activity. Instead, there must be a provision to assign values to a variable after the program is run. The scanf() function reads the user input during the runtime, and assigns the value to a variable.
C User Input Function: The scanf()
C language 将标准输入流识别为 stdin ,并由键盘等标准输入设备表示。C 总是以字符的形式从输入流中读取数据。
The C language recognizes the standard input stream as stdin and is represented by the standard input device such as a keyboard. C always reads the data from the input stream in the form of characters.
scanf() function 使用适当的格式说明符将输入转换为所需的 data type 。
The scanf() function converts the input to a desired data type with appropriate format specifiers.
Syntax of Scanf()
以下是如何在 C 中使用 scanf() 函数 −
This is how you would use the scanf() function in C −
int scanf(const char *format, &var1, &var2, . . .);
User Input Format Specifiers
在格式字符串中使用以下格式说明符 −
Following format specifiers are used in the format string −
Format Specifier |
Type |
%c |
Character |
%d |
Signed integer |
%f |
Float values |
%i |
Unsigned integer |
%l or %ld or %li |
Long |
%lf |
Double |
%Lf |
Long double |
%lu |
Unsigned int or unsigned long |
%lli or %lld |
Long long |
%llu |
Unsigned long long |
Example: User Inputs in C
回到前面的示例,我们将使用 scanf() 函数来接受“price”和“qty”的值,而不是为它们分配任何固定值。
Going back to the previous example, we shall use the scanf() function to accept the value for "price" and "qty", instead of assigning them any fixed value.
#include <stdio.h>
int main(){
int price, qty, ttl;
printf("Enter price and quantity: ");
scanf("%d %d", &price, &qty);
ttl = price * qty;
printf("Total : %d", ttl);
return 0;
}
当运行上述程序时,C 等待用户输入值 −
When the above program is run, C waits for the user to enter the values −
Enter price and quantity:
输入值并按 Enter 后,程序将继续执行后续步骤。
When the values are entered and you press Enter, the program proceeds to the subsequent steps.
Enter price and quantity: 100 5
Total : 500
更重要的是,对于另一组值,您不需要再次进行编辑和编译。只需运行代码,程序将再次等待用户输入。这样,该程序可以使用不同的输入运行任意多次。
What is more important is that, for another set of values, you don’t need to edit and compile again. Just run the code and the program again waits for the user input. In this way, the program can be run any number of times with different inputs.
Enter price and quantity: 150 10
Total : 1500
Integer Input
%d 格式说明符已定义为有符号整型。以下程序读取用户输入并将其存储在整数变量 num 中。
The %d format specifier has been defined for signed integer. The following program reads the user input and stores it in the integer variable num.
Example: Integer Input in C
查看以下程序代码 -
Take a look at the following program code −
#include <stdio.h>
int main(){
int num;
printf("Enter an integer: ");
scanf("%d", &num);
printf("You entered an integer: %d", num);
return 0;
}
运行代码并检查其输出:
Run the code and check its output −
Enter an integer: 234
You entered an integer: 234
如果你输入一个非数字化的值,输出将是“0”。
If you enter a non-numeric value, the output will be "0".
scanf() 函数可以读取一个或多个变量的值。在你提供输入值时,你必须使用空格、标签或 Enter 分隔连续的值。
The scanf() function can read values to one or more variables. While providing the input values, you must separate the consecutive values by a whitespace, a tab or an Enter.
Example: Multiple Integer Inputs in C
#include <stdio.h>
int main(){
int num1, num2;
printf("Enter two integers: ");
scanf("%d %d", &num1, &num2);
printf("You entered two integers : %d and %d", num1, num2);
return 0;
}
运行代码并检查其输出:
Run the code and check its output −
Enter two integers: 45 57
You entered two integers : 45 and 57
或
or
Enter two integers: 45
57
Float Input
对于浮点输入,你需要使用 %f 格式说明符。
For floating point input, you need to use the %f format specifier.
Example: Float Input in C
#include <stdio.h>
int main(){
float num1;
printf("Enter a number: ");
scanf("%f", &num1);
printf("You entered a floating-point number: %f", num1);
return 0;
}
运行代码并检查其输出:
Run the code and check its output −
Enter a number: 34.56
You entered a floating-point number: 34.560001
Example: Integer and Float Inputs in C
scanf() 函数可能读取不同类型变量的输入。在以下程序中,用户输入存储在整型和浮点变量中 -
The scanf() function may read inputs for different types of variables. In the following program, user input is stored in an integer and a float variable −
#include <stdio.h>
int main(){
int num1;
float num2;
printf("Enter two numbers: ");
scanf("%d %f", &num1, &num2);
printf("You entered an integer: %d a floating-point number: %6.2f", num1, num2);
return 0;
}
运行代码并检查其输出:
Run the code and check its output −
Enter two numbers: 65 34.5678
You entered an integer: 65 a floating-point number: 34.57
Character Input
%c 格式说明符读取键盘单个字符。然而,我们必须在格式字符串中的 %c 之前留一个空格。这是因为 %c 转换说明符不会自动跳过任何首个空格。
The %c format specifier reads a single character from the keyboard. However, we must give a blank space before %c in the format string. This is because the %c conversion specifier won’t automatically skip any leading whitespaces.
如果有杂乱的新行在输入流(例如,来自之前的条目)中, scanf() 调用会立刻消耗它。
If there is a stray newline in the input stream (from a previous entry, for example) the scanf() call will consume it immediately.
scanf(" %c", &c);
格式字符串中的空格告诉 scanf 跳过首个空格,首个非空格字符将使用 %c 转换说明符读取。
The blank space in the format string tells scanf to skip the leading whitespace, and the first non-whitespace character will be read with the %c conversion specifier.
Example: Character Input in C
请看以下示例:
Take a look at the following example −
#include <stdio.h>
int main(){
char ch;
printf("Enter a single character: ");
scanf(" %c", &ch);
printf("You entered character : %c", ch);
return 0;
}
运行代码并检查其输出:
Run the code and check its output −
Enter a single character: x
You entered character : x
Example: Multiple Character Inputs in C
以下程序读取两个字符,它们在两个 char 变量中使用空格分隔。
The following program reads two characters separated by a whitespace in two char variables.
#include <stdio.h>
int main(){
char ch1, ch2;
printf("Enter two characters: ");
scanf("%c %c", &ch1, &ch2);
printf("You entered characters: %c and %c", ch1, ch2);
return 0;
}
运行代码并检查其输出:
Run the code and check its output −
Enter two characters: x y
You entered characters: x and y
stdio.h 头文件也提供 getchar() function 。不同于 scanf(), getchar() 没有格式字符串。另外,它读取单个键击而不使用 Enter 键。
The stdio.h header file also provides the getchar() function. Unlike scanf(), getchar() doesn’t have a format string. Also, it reads a single key stroke without the Enter key.
Example: Character Input Using gets()
以下程序将单个键读入 char 变量中:
The following program reads a single key into a char variable −
#include <stdio.h>
int main(){
char ch;
printf("Enter a character: ");
ch = getchar();
puts("You entered: ");
putchar(ch);
printf("\nYou entered character: %c", ch);
return 0;
}
运行代码并检查其输出:
Run the code and check its output −
Enter a character: W
You entered:
W
You entered character: W
你也可以使用未格式的 putchar() 函数打印单个字符。
You can also use the unformatted putchar() function to print a single character.
Example: Reading a Character Sequence
以下程序显示了如何读取一系列字符,直到用户按下 Enter 键:
The following program shows how you can read a series of characters till the user presses the Enter key −
#include <stdio.h>
int main(){
char ch;
char word[10];
int i = 0;
printf("Enter characters. End by pressing the Enter key: ");
while(1){
ch = getchar();
word[i] = ch;
if (ch == '\n')
break;
i++;
}
printf("\nYou entered the word: %s", word);
return 0;
}
运行代码并检查其输出:
Run the code and check its output −
Enter characters. End by pressing the Enter key: Hello
You entered the word: Hello
String Input
还有一个 %s 格式说明符,它将一系列字符读取到 char 数组中。
There is also a %s format specifier that reads a series of characters into a char array.
Example: String Input Using scanf()
以下程序接受键盘的 string 输入 -
The following program accepts a string input from the keyboard −
#include <stdio.h>
int main(){
char name[20];
printf("Enter your name: ");
scanf("%s", name);
printf("You entered the name: %s", name);
return 0;
}
运行代码并检查其输出:
Run the code and check its output −
Enter your name: Ravikant
You entered the name: Ravikant
C 使用空格作为分隔字符。因此,如果你尝试输入包含空格的字符串,那么只有空格之前的字符将存储为该值。
C uses the whitespace as the delimiter character. Hence, if you try to input a string that contains a blank space, only the characters before the space are stored as the value.
Enter your name: Ravikant Soni
You entered the name: Ravikant
gets() function 克服了这个限制。这是一个未格式化的字符串输入函数。所有字符(直到你按 Enter)都存储在该变量中。
The gets() function overcomes this limitation. It is an unformatted string input function. All the characters till you press Enter are stored in the variable.
Example: String Input Using gets()
请看以下示例:
Take a look at the following example −
#include <stdio.h>
#include <stdlib.h>
int main(){
char name[20];
printf("Enter your name: ");
gets(name);
printf("You entered the name: %s", name);
return 0;
}
运行代码并检查其输出:
Run the code and check its output −
Enter your name: Ravikant Soni
You entered the name: Ravikant Soni
用户输入是 C 编程中应用程序一个重要的方面。在本章中,我们使用不同的示例解释了格式化和非格式化的控制台输入函数, scanf() 、 getchar() 和 gets() 的使用。
User input is an important aspect of an application in C programming. In this chapter, we explained the usage of formatted and unformatted console input functions, scanf(), getchar(), and gets() with different examples.