I am developing windows console based application. And I need to read characters (entered by kbd) on console. I am using scanf function. Is there any wrong in using C library in Windows application?
Please let me know.
Printable View
I am developing windows console based application. And I need to read characters (entered by kbd) on console. I am using scanf function. Is there any wrong in using C library in Windows application?
Please let me know.
Using scanf is ok in console (that is what you meant, right? Not windows API?) though I suggest you use fgets instead. Scanf is easily crashed.
There is nothing wrong with using C standard libraries in a console application. That is how they are written.
As long as you stick with the standard C libraries, you will be able to take that code and compile it on any machine, regardless of OS.
Where you get into trouble is when you start using platform specific libraries and header files.
IE:
#include <windows.h> // Windows
#include <sys/*.h> // Unix & Linux
Now, as far as scanf goes, there are better ways:
Instead of doing this:
Use fgets, and sscanf if they are numerical values (integers, floats, etc).Code:scanf("%d", &val);
Or use straight fgets to read in strings:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* fgetstring -- function that uses fgets, but removes the new-line character, and places a null terminating character at the end of the string */
char* fgetstring(char* s, size_t size, FILE* stream)
{
char* status;
status = fgets(s, (int)size, stream);
if(status != NULL)
{
size_t strlength = strlen(s);
if(s[strlength - 1] == '\n')
{
s[strlength - 1] = '\0';
}
}
return status;
}
int main(void)
{
int iVal;
float fVal;
char myString[20];
char tempString[1024];
printf("Enter an integer value\n");
fgetstring(tempString, sizeof(tempString), stdin);
sscanf(tempString, "%d", &iVal);
printf("Enter a Floating point value\n");
fgetstring(tempString, sizeof(tempString), stdin);
sscanf(tempString, "%f", &fVal);
printf("Enter a string of characters\n");
fgetstring(myString, sizeof(myString), stdin);
/* Use this if you want to store the string in temporary
memory first
fgetstring(tempString, sizeof(tempString), stdin);
memcpy(myString, tempString, sizeof(myString));*/
printf("iVal = %d\n", iVal);
printf("fVal = %.2f\n", fVal);
printf("myString = %s\n", myString);
return 0;
}
Hope that helps.
Thanks for reply.
But after building the code in VC++ 6.0. I got following error.
\microsoft visual studio\vc98\include\stdlib.h(298) : error C2040: 'malloc' : 'void *(unsigned int )' differs in levels of indirection from 'void *(unsigned int )'
c:\program files\microsoft visual studio\vc98\include\string.h(105) : error C2040: 'strcpy' : 'char *(char *,const char *)' differs in levels of indirection from 'char *(char *,const char *)'
So is there any restriction on the code.
Thanks,
you're compiling your code as C? (*.c) or as C++? (*.cpp)
Compiling code as C