c - 如果 scanf 类型错误,我应该如何打破循环?(C)
问题描述
这是我的代码...我尝试了is nan,我想的一切,也使用了一个字符串,然后用atof和strtof将其转换为浮点数,如果用户在do while循环中插入任何字符串,我将停止循环,甚至只是让代码更好会很好,谢谢:)
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
void shift(float* array,char dir,int size);
int main(){
int n=0,i;
float *array=NULL,val;
char dir[20];
int numeric;
do{
printf("Insert a new element for the array ('stop' to stop): ");
scanf ("%f", &val);
if(isnanf(val)) break;
vettore = (float*) realloc( vettore,(++n)*(sizeof(float)) );
vettore[n-1] = val;
} while (isnan(val)==0);
if(n>0){
printf("In which direction would to shift the array to? ");
scanf("%s",dir);
shift(vettore,dir[0],n-1);
printf("Here is the array shifted to %s: ",dir);
for(i=0;i<n;i++) printf("%d, ", vettore[i]);
free(vettore);
}else printf("You haven't inserted any number! ");
return 0;
}
void shift(float* array,char dir,int size){
int temp,i;
if(dir=='d'){
temp=array[size];
for(i=size;i>0;i--) array[i]=array[i-1];
array[0]=temp;
}else{
temp=array[0];
for(i=0;i<size;i++) array[i]=array[i+1];
array[size]=temp;
}
}
代码应该是这样的: 为数组插入一个新元素: 1 为数组插入一个新元素: 2 为数组插入一个新元素: 3 为数组插入一个新元素: 4 为数组插入一个新元素array: stop 你想把数组移到哪个方向?(d 代表右边,其他东西代表左边) left here 数组向左移动:2、3、4、1,
解决方案
你可以这样做
while( puts("Inserire un nuovo elemento del vettore ('stop' per terminare): ") && scanf("%f", &val) == 1) {
vettore = (float*) realloc( vettore,(++n)*(sizeof(float)) );
vettore[n-1] = val;
}
//Then clear the buffer from the "stop"
while((c = getchar()) != '\n' && c != EOF);