It would be nice to cast a string (array of chars) to an int when reading from files or taking input is this possible.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SIZE 500
int main(void)
{
FILE* pfile;
pfile = fopen("/tmp/code","r"); //open file
char *stringBuffer = (char *)malloc(SIZE * sizeof(char)); //dynamic string
char ch;
int i = 0;
ch = getc(pfile); //read file
while(ch != EOF) //until end
{ //pass into string
counter++;
stringBuffer[i] = ch;
ch = getc(pfile);
i++;
}
fclose(pfile); //resize string
int stringSize = (int)(sizeof(stringBuffer)/sizeof(char));
stringBuffer = (char *)realloc(stringBuffer,(stringSize * sizeof(char)));
printf("the string works: %s \n",stringBuffer);
int intger = (int)*stringBuffer; //this is what i want to work!!!!
//but more like
//int intger = (int)stringBuffer;
printf("the intger doesn't work if more than 1 decimal place: %i \n",(intger - 48));
free(stringBuffer);
return(0);
}
~
~
I do realize I could 1.cast the char as int & convert from ASCII to real number 2.multiplier each (now int) by is decimal place (determined by array position) 3.add ints together for example (warning this code is kinda ugly, I haven't look twice at it yet and is just a test so far)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#define SIZE 500
int main(void)
{
FILE* pfile;
pfile = fopen("/tmp/code","r");
char *stringBuffer = (char *)malloc(SIZE * sizeof(char));
char ch;
int i = 0;
ch = getc(pfile);
while(ch != EOF)
{
stringBuffer[i] = ch;
ch = getc(pfile);
i++;
}
fclose(pfile);
int stringSize = (int)(sizeof(stringBuffer)/sizeof(char));
stringBuffer = (char *)realloc(stringBuffer,(stringSize * sizeof(char)));
printf("the string works: %s \n",stringBuffer);
int multi;
int sum;
for(int x =0; x < stringSize; x++)
{
int intger = ((int)stringBuffer[((stringSize - 1) - x)] - 48);
if( x != 0 )
{
multi = (int)pow(10,x);
sum += ( multi * intger );
}
else
sum += intger;
}
printf("the int works: %i \n",sum);
free(stringBuffer);
return(0);
}
but still casting as string as int would be nice(I assume c++ has this?).