[英]Checking user input in C
I would like to ask: How to check user input , which is stored in array with another array, I have defined... Something like this: User will give input 10,20,5 and I need to check, if it is from this array {5,10,20,50} 我想问一下:如何检查用户输入(已与另一个数组存储在数组中),我已定义...诸如此类:用户将输入10,20,5,我需要检查输入是否来自这个数组{5,10,20,50}
Any help appreciated :). 任何帮助表示赞赏:)。 Thanks 谢谢
#include <stdio.h>
#include <stdlib.h>
int main ()
{
float bill;
int notes[] = {100, 50, 20, 10, 5, 2, 1, 0.50, 0.20, 0.10, 0.05, 0.02, 0.01};
printf("Enter value of your bill: ");
scanf("%f",&bill);
if (bill<0 || bill>10000)
{
return -1;
}
else
{
for (int i=0; i<8;i++)
{
if (bill!=notes[i])
{
break;
}
}
}
return 0;}
To get user input you must use the scanf()
function. 要获得用户输入,必须使用scanf()
函数。 Here is an example, where it asks for three separate numbers. 这是一个示例,其中要求输入三个单独的数字。
#include <stdio.h>
int main(void) {
int one, two, three;
printf("Enter first number: ");
scanf("%d", &one);
printf("Enter second number: ");
scanf("%d", &two);
printf("Enter third number: ");
scanf("%d", &three);
printf("one: %d, two: %d, three: %d\n", one, two, three);
return 0;
}
Will produce the following: 将产生以下内容:
Enter first number: 1
Enter second number: 2
Enter third number: 3
one: 1, two: 2, three: 3
Here is another way to use scanf, but the user must be more specific about how they answer the prompt. 这是使用scanf的另一种方法,但是用户必须更具体地了解他们如何回答提示。
#include <stdio.h>
int main(void) {
int one, two, three;
printf("Enter three numbers separated by a comma: ");
scanf("%d,%d,%d", &one, &two, &three);
printf("one: %d, two: %d, three: %d\n", one, two, three);
return 0;
}
Will produce the following: 将产生以下内容:
Enter three numbers separated by a comma: 1,2,3
one: 1, two: 2, three: 3
UPDATE: Because you posted code that shows you know how scanf works. 更新:因为您发布的代码向您展示了scanf的工作原理。
To search through an array you must use a for loop. 要搜索数组,必须使用for循环。
#include <stdio.h>
int main(void) {
float n = 100;
int numbers[] = {5, 10, 20, 50, 100, 200, 500};
int i;
for (i = 0; i < 7; i++) {
if (n == numbers[i]) {
printf("Matching index for %f at %d\n", n, i);
}
}
return 0;
}
#include<stdio.h>
int main(){
int inp,i,j;
int foo=0;
int arr[]={5,10,20,30};
for(j=0;j<3;j++){
scanf("%d",&inp);
for(i=0;i<4;i++)
{
if(inp == arr[i])
{
foo=1;
break;
}
}
if(foo==0)
break;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.