-
atoi or scanf()
Why do I sometimes see atoi used instead of scanf().
struct store{
int number;
};
int main()
{
struct store shop;
char age[10];
printf("input a number:>");
gets(age); /* ok. should be fgets */
shop.number=atoi(age); /* why this */
scanf("%d",&shop.number), /* instead of this */
}
/* also does atoi work like this */
/* scans the array age element by element 0=49, 1=50, 2=51 */
/* converts these ascii values into there digit equivalents 1,2,3 */
/* and add each one to shop.number */
thanks for all the guidence guys.
-
>>printf("input a number:>");
>>gets(age); /* ok. should be fgets */
>>shop.number=atoi(age); /* why this */
>>scanf("%d",&shop.number), /* instead of this */
gets() returns a string, not an integer which is what was entered for input, atoi() will change a string into an integer. scanf can read an integer directly. Which one is used really depends on style in this particular case, but you can't use gets without atoi to get an integer.
-
Here the atoi() function is not used to scan in an integer, but to convert a string that was inputted using gets().
I am pretty damn sure that atoi() can NEVER be used instead of scanf() or any other input/output function for that matter.
printf("input a number:>");
gets(age); /* gets a string from the user */
shop.number=atoi(age); /* converts that string to an int *
* and stores it in shop.number */
scanf("%d",&shop.number), /* scans another int into *
* into shop.number */
I don't understand why someone would want to store the converted string into an int, that is overwritten with the next statement.:confused:
-
> I don't understand why someone would want to store the
> converted string into an int, that is overwritten with the next
> statement.
They weren't saying to actually have atoi() followed by the scanf.
They were asking, which of the two lines is preferred.
Quzah.
/*god I hate this board. i keep forgetting to sign in. They need to
have a better cookie.*/
-
Re: atoi or scanf()
/* THE FOLLOWING PROGRAMME IS TO SOLVE A PROBLEM THAT CAN'T BE SOLVED WITHOUT THE USE OF atoi. THIS PROGRAMME DOESN'T ALLOW THE USER TO ENTER ANYTHING OTHER THAN
0 TO 9 .*/
#include <stdio.h>
#include <conio.h>
int main(void)
{
char ch[6];
int unsigned number; //unsigned because age can't be negative
do{
int static count;
printf ("enter the age: ");
ch[count]=getch();
if(ch[count]==13){ //checking if enter is pressed
ch[count]='\0';
break;
};
if((ch<48) || (ch>57)) { //checking if the number is 0 to 9
printf ("error!");
ch[count]='\0';
count-=1;
}
ch[count+1]='\0'; //a string is terminated by a null
gotoxy(1,2);
printf ("%s",ch); //printing the string
count+=1; //increasing the value of count by 1;
}while(1); //no condition is need since pressing enter will do that
number=atoi(ch); //converting the string into integer
gotoxy(1,4);
printf ("Here is the perfect age: %d",number);
getch(); //wait for a ending key press
return 0;
}
;)