-
SPRINTF help please.
OK, my compiler is giving two warnings:
>>>> warning C4047: 'function' : 'const char *' differs in levels of indirection from 'unsigned int '
>>>>warning C4024: 'sprintf' : different types for formal and actual parameter 2
I was under the impression i could use sprintf to convert a string to an int?
I have used strtol in the past and it has always worked, but i want an INT not a LONG INT.
Here's the code:
Code:
#include<stdio.h>
#include<stdlib.h>
int main(void)
{
int iTempr, iMaxTempr, iMinTempr, iInputError;
char cBuff01[BUFSIZ];
do
{
printf("> Please enter the temperature:");
fgets(cBuff01, sizeof(cBuff01), stdin);
if (sscanf(cBuff01, "%d", &iTempr) == 1);
if (cBuff01[0] != '\n')
{
if (iTempr > iMaxTempr)
{
iMaxTempr = iTempr;
}
else if (iTempr < iMinTempr)
{
iMinTempr = iTempr;
}
iInputError = 0;
}
else
{
printf("\n\tInvalid Input. Please try again.\n\n");
iInputError = 1;
}
}while(iInputError == 1);
printf("%d", iTempr);
return 0;
}
-
Looks like you are getting snprintf and sprint confused.
I think (in your code) you meant
Code:
snprintf(cBuff01, sizeof(cBuff01), "%d", iTempr);
-
> sprintf(cBuff01, sizeof(cBuff01), "%d", iTempr);
If you're trying to get an integer OUT of the string (seems likely, given the previous line is fgets), then you need
if ( sscanf(cBuff01, "%d", &iTempr) == 1 )
> iTempr = cBuff01[BUFSIZ];
Remove this line, it does nothing useful, and is an out-of-bound array access anyway.
-
changing the line
Code:
sprintf(cBuff01, sizeof(cBuff01), "%d", iTempr);
to
Code:
sprintf(cBuff, "%d", iTempr);
gave me no warnings, but no matter what my result came out as '-52'
:S
-
-
I've edited my first post (the code), is this how you meant to use it? I will read up about sscanf now too :D
-
Sorry for double post, how would i change my code so that if they enter a letter or string, it loops again. I am not sure how to do this error checking method involving sscanf and fgets.
-
By adding an 'else' to the if statement you've managed to neuter.