It should give me the number of inputs entered by the user. But it gives 100. I compiled with gcc.
#include <stdio.h>
int arr[100];
int count=0;
int max=100;
int main(){
int i, input;
printf("Enter integer values one by one, q to quit.\n");
for(i=0;i<max;i++){
scanf("%d",&input);
arr[i]=input;
if(input=='q')break;
count++;
}
printf("You entered %d values.\n开发者_运维知识库",count);
return 0;
}
If you are reading into a numeric variable, it can't really have the value 'q', so your test won't work. If you want to write code like this, you should read user input into a string, check to see if the string contains "q" and if not convert it to an integer.
scanf
has a return value. Use it to test if scanf was actually able to parse anything. In your scenario, 'q' will never be stored in the variable input
, being it as a char or numerical representation. You cannot read "q" as "%d" and therefore scanf will silently fail.
Test for the return value of scanf to decide for a break
.
scanf %d does not understand 'q'. You can check the return value of scanf though - if it returns 0 the user did not enter a valid number.
If only q and not other non-numeric strings should terminate the loop, read into a string and check if it's q and if not convert it to an int with atoi().
Cute. Entering 'q'
causes the scanf to fail, with input
left at whatever the last value was. This broken loop continues to the end of the range. The test input=='q'
never succeeds, of course.
:) Let me modify this program like this:
#include <stdio.h>
int arr[100];
int count=0;
int max=100;
int main(){
int i, input;
printf("Enter integer values one by one, -1 to quit.\n");
for(i=0;i<max;i++){
scanf("%d",&input);
arr[i]=input;
if(input==-1)break;
count++;
}
printf("You entered %d values.\n",count);
return 0;
}
You can't use a numeric var to get a char value. If you change it just like this, it will work. :)
scanf will return 0 in your code when the input character does not match the conversion specification. But, the next call to scanf will resume searching immediately after the last converted character. Therefore, you can try the below code:
#include <stdio.h>
int arr[100];
int count=0;
int max=100;
int main(){
int i, input, ret;
char end;
printf("Enter integer values one by one, q to quit.\n");
for(i=0;i<max;i++)
{
ret = scanf("%d",&input);
if (!ret)
{
scanf("%c", &end);
if ( end == 'q')
break;
else
continue;
}
arr[i]=input;
count++;
}
printf("You entered %d values.\n",count);
return 0;
}
By doing this, you can make sure that control does not come out of the loop unless you enter q and only legitimate values are copied to the array.
you exit the program by typing the ascii value for 'q' not q/
精彩评论