In my code below I am trying to ignore new lines. Is there a better way of doing this?
do
{
scanf("%c",&wouldCount);
} while(wouldCount == '\n');
original code
#include <stdio.h>
int main()
{
char Yes = 'Y';
char wouldCount;
int counter;
int start;
int end;
int increment;
const END_DEFAULT = 1;
const INCREMENT_DEFAULT = 1;
printf("Woul开发者_高级运维d you like to count?");
scanf("%c",&wouldCount);
while(wouldCount == 'Y' || wouldCount == 'y')
{
printf("Please enter start number.");
scanf("%d",&start);
printf("Please enter a number you would like to stop at?");
scanf("%d",&end);
printf("Please enter a number to increment by.");
scanf("%d",&increment);
if(end < start)
{
end = start + END_DEFAULT;
}
if(increment <= 0)
{
increment = INCREMENT_DEFAULT;
}
for(counter = start; counter < end; counter += increment)
{
printf("%d\n",counter);
}
printf("Would you like to count?");
do
{
scanf("%c",&wouldCount);
} while(wouldCount == '\n');
}
return 0;
}
you could change scanf("%c",&wouldCount); to scanf("\n%c",&wouldCount); as well as forgo the do/while loop. This will tell scanf to ignore an enter with no character entered.
see scanf c++ reference
精彩评论