Casting from double to char

Hi,

i am trying to save a matrix of doubles to a file with name Output.txt in C programming.

My code until now is and i have the questions as comments:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

// matrix[i][j] contain doubles and its size is [100][100], so N=100.

FILE *out_file;
	
out_file = fopen("Output.txt", "w");
if (out_file == NULL) {
   fprintf(stderr,"Can not open output file\n");
   exit (8);
}
	
for(i=0;i<N;i++)
   for(j=0;j<N;j++)
      fputc(matrix[i][j],out_file);// what function should i use here ? How to cast from character to double ??

fclose(out_file);


Any idea please?

Thanks.
Last edited on
The error i receive from the compiler is the following:

warning: passing argument 1 of fputc makes integer from pointer without a cast


How to convert the matrix elements from double to char?
Casting from double to char
How to cast from character to double ?


Do you want double to char, or char to double?

Here is double to (pointer to array of) char:

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
#include <sstream>

int main()
{
std::ostringstream s;
 double aDoubleValue = 4.385;
s << aDoubleValue;
std::string output = s.str();
const char* inCharPointerFormat = output.c_str();
std::cout << inCharPointerFormat;
return 0;
}
Last edited on
i am looking in C programming. I have a matrix which saves double numbers and i want to save them to .txt file.

I dont know which function should i use to convert double to char, in order to be able to save them in the .txt file.

i tried the code which i provided before but fputs is working only with characters. Any idea ?
1
2
3
double a = 1.41;
char x[50];
sprintf(x,"%13.5f",a);
So you can't use C++ ??

Well, you're already using fprintf for your errors. You could use that for the output, too. Rather than converting and then outputting as separate steps.

1
2
3
for(i=0;i<N;i++)
   for(j=0;j<N;j++)
      fprintf(out_file, "%f\n", matrix[i][j]); // assuming one value per line here 

Last edited on
Topic archived. No new replies allowed.