Your main problem is that your loop steps through all of the buffer buf instead of only stepping through the '\0' terminated string it contains.
For example, if we assume buf was declared as char buf[100]; and we enter the string "3924456639" then buf will contain:
{'3','9','2','4','4','5','6','6','3','9','\n','\0', ... and 88 bytes of garbage}
then your loop will correctly step through the digits and ignore the '\n'. But then it does not stop. Since '\0' is neither ' ' nor '\n', temp gets multiplied by ten and '\0' - '0' is added. And the same goes for every one of those 88 bytes of garbage that is neither ' ' nor '\n'.
To fix this, change:
for(int i = 0; i < sizeof buf ;i++){
to:
for(int i = 0; i < strlen(buf) ;i++){
or:
for(int i = 0; buf[i] != '\0' ;i++){
(Remember to #include <string.h> if you want to use strlen().)
Note:
- Your minor problem is that
long might be too small for your number.
- Like @KALALEX pointed out, you could use
strtol().