Quick question about pointers

Im reading an input file that has the following co-ordinates

2.5 1.5
-1.5 1.5
2.0 3.0

I need to come up with new coordinates and print them in an out file,
how do I write the function so that I would get 3 new co-ordinates instead of one co-ordinate

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
 #include<stdio.h>
#include<math.h>

void transform(float x, float y,float *pu,float *pv);

int main(void)
{
	
	float x, y, u, v;
	
	FILE* fin = fopen("vectorsin.txt","r");
	FILE* fout =fopen("vectorsout.txt","w");
	
	fscanf(fin,"%f %f",&x, &y);
	
	transform(x, y, &u, &v);
	
	fprintf(fout,"%f %f\n", u, v);
	
	return 0;
}

void transform(float x, float y, float *pu, float *pv)
{
	float answer_1, answer_2;


	answer_1 = (x - y)/2.0;
	answer_2 = (x + y)/2.0;

	*pu = answer_1;
	*pv = answer_2;
	
	return;
}
Hi,

..... how do I write the function so that I would get 3 new co-ordinates instead of one co-ordinate


You need a loop for that. If you just want 3 lines read, then a for loop will do. Much better a while loop to read the whole file. Look at the documentation for fscanf for a return value that signifies the end of file has been reached, use that value as your end condition in the while loop.

When opening a file, always check to see that it worked.

When using any of the scanf family of functions, make use of it's return value to see that it worked.

Like wise with any of the printf functions. Consider using snprintf to print to a string, if that works, then print the string to the file with fprintf. That way you can avoid printing the wrong info to the file if you have a correct but wrongly intentioned format specifier.

Use const where ever possible:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
//void transform(float x, float y, float *pu, float *pv)
void transform(const float x, const  float y, float *pu, float *pv)
{
	/* float answer_1, answer_2; */


	/*answer_1 = (x - y)/2.0;
	answer_2 = (x + y)/2.0; */

	/*   *pu = answer_1;    */
        *pu = (x - y)/2.0;
	/*    *pv = answer_2;   */
	*pv = (x + y)/2.0;
	/* return;  unnecessary  */
}


Is there a particular reason why you are using float ? double is the default and preferred type. One might use float if a library requires it (Graphics lib say) , or if you have billions of them. The reason double is preferred, is because the precision of float is easily exceeded.

Good Luck !!
Topic archived. No new replies allowed.