Well, I'm trying to use strtol to convert a string to long int, following
FAQ > How do I get a number from the user (C) - Cprogramming.com
Code:
#include <stdio.h>
#include <stdlib.h>
int getInt(char msg[40], long int *theNum);
int main(void) {
long int theNum;
getInt("Type a num: ", &theNum);
printf("theNum: %ld\n\n", theNum);
return 0;
}
int getInt(char msg[40], long int *theNum) {
char buf[BUFSIZ];
char *endPtr;
printf (msg);
if (fgets(buf, sizeof(buf), stdin) != NULL) {
theNum = strtol(buf, (void *)&endPtr, 10);
if (buf[0] != '\n' && (*endPtr == '\n' || *endPtr == '\0'))
printf ("Valid number of %ld entered\n", (long int)theNum);
else printf ("The number was %ld, followed by %s\n", (long int)theNum, endPtr);
}
return theNum;
}
My intention is the have theNum to be updated without having
to do
Code:
theNum = getInt(arg, arg);
but rather just passing its
address, like in
Code:
getInt("msg", &theNum);
I'm not being able to change the value of theNum (it always has garbage), and the compiler is giving me the following warnings:
getIntStrtol.c: In function ‘getInt’:
getIntStrtol.c:25:16: warning: assignment makes pointer from integer without a cast [enabled by default]
getIntStrtol.c:32:5: warning: return makes integer from pointer without a cast [enabled by default]
I understand what the messages mean, but I don't understand why.
By the way, If I assign the return value to a long int variable, then I can print that variable just fine.
EDIT: This version seems to work:
Code:
#include <stdio.h>
#include <stdlib.h>
int getInt(char msg[40], long int *theNum);
int main(void) {
long int theNum;
long int num;
num = getInt("Type a num: ", &theNum);
printf("theNum: %ld\n\n", theNum);
printf("num: %ld\n\n", num);
return 0;
}
int getInt(char msg[40], long int *theNum) {
char buf[BUFSIZ];
char *endPtr;
printf (msg);
if (fgets(buf, sizeof(buf), stdin) != NULL) {
*theNum = strtol(buf, &endPtr, 10);
if (buf[0] != '\n' && (*endPtr == '\n' || *endPtr == '\0'))
printf ("Valid number of %ld entered\n", *theNum);
else printf ("The number was %ld, followed by %s\n", *theNum, endPtr);
}
return *theNum;
}