Reputation: 598
I was trying to make a simple program to change the base of a number (i,e I give the bases 2 and 5, and the number 101 and I should get 10) and when doing the function to read the bases I get the following: If I type in correctly the data it works, if I don't (for example, I type "231") the program goes into an infinite loop, why is this happening?
#include <stdio.h>
int main(void)
{
int base1,base2;
readBases(&base1,&base2);
printf("%d%d\n",base1,base2);
return 0;
}
void readBases(int *baseOrig, int * baseDest)
{
int aux1,aux2,flag;
do
{
printf("Type in the bases, in the format <a>b:");
flag=scanf("<%d>%d",&aux1,&aux2);
if(aux1<2||aux1>10||aux2<2||aux2>10)
{
flag=0;
printf("Invalid data.\n");
}
}while(flag!=2);
*baseOrig=aux1;
*baseDest=aux2;
}
Upvotes: 0
Views: 72
Reputation: 13073
flag=scanf("<%d>%d",&aux1,&aux2);
reads as much of the input stream as it can, and returns the number of converted fields.
If it can't read anything, then it will not progress input - getting stopped. You need some way of reading the data - safely.
Line termination works quite well.
while( fgets( buffer, sizeof( buffer), stdin ) != NULL ){
flag = sscanf( buffer, "<%d>%d",&aux1,&aux2);
}
Upvotes: 1