Hi,
Found this forum very useful in my studies of C - language. Thank you for that.
Well now I have a problem of my own.
I am writing a program that can handle large numbers that can be 300 characters long.
The program is suppose to read the first number from file and then add the second number to it that user inputs and write it back to the file. Now, I have gotten to the point where I am supposed to write that number back to the file. I am kind of stuck with that.
Here is type definition for the "large number"
#define MAX 300
typedef int BigNumber[MAX];
BigNumber N;
- #define MAX 300
- typedef int BigNumber[MAX];
- BigNumber N;
and here is the function where i read the number from the the file.
void readbignumberFromfile(BigNumber N, FILE * file)
{
char str[MAX];
int i;
fscanf(file,"%s", str);
N[0] = strlen(str);
for (i = strlen(str)-1; i>=0; i--)
N[N[0]-i] = chrtoint(str[i]);
}
int chrtoint(char a)
{
int i;
for (i = 48; i<=57; i++){
if ( (char)(i)==a) return i-48;
}
return -1;
}
- void readbignumberFromfile(BigNumber N, FILE * file)
- {
- char str[MAX];
- int i;
- fscanf(file,"%s", str);
-
- N[0] = strlen(str);
-
- for (i = strlen(str)-1; i>=0; i--)
- N[N[0]-i] = chrtoint(str[i]);
- }
- int chrtoint(char a)
- {
- int i;
- for (i = 48; i<=57; i++){
- if ( (char)(i)==a) return i-48;
- }
- return -1;
- }
how could it be done easily to write the number back to the file. Should convert the number from int to char and then write it back or how should it be done?
I tried this kind of function but it only adds some kinf of squares to file.
void writebignumberTofile(BigNumber N, FILE * file)
{
int i;
for (i = N[0]-1; i>=0; i--)
putc(N[i], file);
}
- void writebignumberTofile(BigNumber N, FILE * file)
- {
- int i;
- for (i = N[0]-1; i>=0; i--)
- putc(N[i], file);
- }