【发布时间】:2018-12-15 06:06:32
【问题描述】:
我正在课堂上学习 c 语言,我创建了一些代码来在其他数组中查找某个数字,但是当我尝试使用 char 值时,我的代码与使用 int 值的方式不同。
这是我的代码:
#include<stdio.h>
int main () {
int num, i, j;
char a[99], ele;
printf("Enter the Character element:");
// get the length of array by the num value
scanf("%d", &num);
printf("Enter the values: \n");
// a loop for getting values for our a[array] line by line
for ( i = 0 ; i < num ; i++ ) {
// get value by index i for array a index by index
//printf("%d\t", (i+1));
//if ( i + 1 == num ) {
// scanf("%c", &a[i]);
//} else {
scanf("%c", &a[i]);
//}
}
printf("Enter the Character elements to be searched:");
// get the value for ele, to use ele for searching inside our a[array]
scanf("%c", &ele);
// we need to set i to 0 for our while loop
j = 0;
// use the while loop to
while ( j < num && ele != a[j]) {
j++;
}
if ( j < num ) {
printf("Character found at the location = %d\n\n\n", j + 1);
} else {
printf("Character Not Found!\n\n\n");
}
return 0;
}
我尝试修复了很多次,但每次都出现错误,所以上面的那个是有效的,但它在输入过程中会限制一些输入值。
【问题讨论】:
-
请添加一个示例输入,您的代码不符合您的预期
-
如果我在这一行的 %c 之后添加 \n (scanf("%c", &a[i]);) 输入将固定但在输入最后一个值后第二个 scanf 这个 ( scanf("%c", &ele);) 不起作用,程序将结束。
-
在运行此程序时仔细考虑键盘上按下的每个键。这里不仅仅是字母数字字符,从输入您的号码
num时按 Enter 开始。 Read this answer. -
请花点时间了解
scanf()的行为 -
这里的要点是,有充分的理由,
%c指令与大多数其他scanf指令的不同之处不仅仅是对应变量的预期类型。
标签: c arrays search input char