Since almost all C functions designed to get data from stdin
are bad / flawed:
gets
- the less said about this the betterscanf
- no checks for buffer overflow and'\n'
constantly remaining instdin
, screwing up nextscanf
sscanf_s
- pretty much the same, but with buffer overflow checksfgets
appends a'\n'
to thestring
gets_s
doesn't have the previous problem, but useless for other streams
I decided to write my own function that would at least be usable to read numbers from stdin
:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void *scano(char mode);
int main()
{
// int *num = (int *) scano(sData, 'd');
float *num = (float *)scano('f');
printf("Half: %f", *(num)/2);
return 0;
}
void *scano(char mode){
char sData[20];
fgets(sData, 20, stdin);
*(sData + strlen(sData) - 1) = '\0'; //get rid of the '\n' before the '\0'
switch(mode){
case 'd':{
int *dataI = (int *)malloc(sizeof(int));
*dataI = atoi(sData);
return dataI;
}
case 'f':{
float *dataF = (float *)malloc(sizeof(float));
*dataF = atof(sData);
return dataF;
}
case 'D':{
//double...
}
}
}
The function is of type void *
because that's the only convenient way to have it return
different data types.
The function is obviously unfinished for other data types, but I have some questions first:
- How can the algorithm of the function be improved?
- Don't I need to
free()
in everycase
? I'm aware allocated memory needs to be freed, but when working with lists,free()
was only used to deleteNodes
, when creatingNodes
, nofree()
was called after amalloc()
. - Is it fully safe? If not, how can it be made safe?