循环输出出现的错误
循环输出出现的异常
新手请各位前辈指教。
初始化一个字符数组。要求输入正确后,再输入下一个,如果输入不正确重新输入。具体实现代码如下面的程序段。
但在调试的时候当输入一个不是字符的数字,却出现如下的显示:
Wrong type please input again!
char[0] = Wrong type please input again!
char[0] =
而按预期的是希望出现:
Wrong type please input again!
char[0] =
的回显的!
void initArr(char arr[], int n) {
int i;
char j;
printf("initiate the array:\n");
i = 0;
while(i < n) {
printf("char[%d] = ", i);
scanf("%c", &j);
if((j >= 'a' && j <= 'z') || (j >= 'A' && j <= 'Z')) {
arr[i] = j;
i ++;
} else if(j = '') {
continue;
} else {
printf("Wrong type please input again!");
j = '';
}
printf("\n");
}
printf("\n");
}
------解决方案--------------------
加入fflush(stdin);
新手请各位前辈指教。
初始化一个字符数组。要求输入正确后,再输入下一个,如果输入不正确重新输入。具体实现代码如下面的程序段。
但在调试的时候当输入一个不是字符的数字,却出现如下的显示:
Wrong type please input again!
char[0] = Wrong type please input again!
char[0] =
而按预期的是希望出现:
Wrong type please input again!
char[0] =
的回显的!
void initArr(char arr[], int n) {
int i;
char j;
printf("initiate the array:\n");
i = 0;
while(i < n) {
printf("char[%d] = ", i);
scanf("%c", &j);
if((j >= 'a' && j <= 'z') || (j >= 'A' && j <= 'Z')) {
arr[i] = j;
i ++;
} else if(j = '') {
continue;
} else {
printf("Wrong type please input again!");
j = '';
}
printf("\n");
}
printf("\n");
}
------解决方案--------------------
加入fflush(stdin);
- C/C++ code
... fflush(stdin); scanf("%c", &j); ...
------解决方案--------------------
- C/C++ code
#include <stdio.h> void initArr(char arr[], int n) { int i; char j; printf("initiate the array:\n"); i = 0; while(i < n) { printf("char[%d] = ", i); fflush(stdin);//清空缓冲区 scanf("%c", &j); if((j >= 'a' && j <= 'z') || (j >= 'A' && j <= 'Z')) { //只识别英文字母 arr[i] = j; i ++; } /*else if(j == ' ') { //= -> == continue; }*/ else { printf("Wrong type please input again!"); //j = ' '; } printf("\n"); } printf("\n"); } int main() { char arr[20]; initArr(arr,5); return 0; }
------解决方案--------------------
i = 0;
while(i < n) {
printf("char[%d] = ", i);
只要你的n>0,printf("char[%d] = ", i);是肯定会输出的.
在这之后才进行的判断你的输入是否符合要求.所以输入不符合要求的值后就显示了char[xxx] = xxxxxxxxxx