Jump to content

how to create txt file

- - - - -

  • Please log in to reply
2 replies to this topic

#1
aruwin

aruwin

    Learning Programmer

  • Members
  • PipPipPip
  • 42 posts
I wanna create a txt file in c++ but something wne wrong.My driver does not detect the txt file :(

Here's the code
#include <stdio.h>
#include <math.h>
#define G 9.801
#define PI 3.142

int main() {
float t, x, y, angle, Vo, deltat;
int i;
FILE* fp;

printf( "t = " );
scanf("%f", &t);

printf( "deltat = " );
scanf("%f", &deltat);

printf("initial velocity = ");
scanf("%f", &Vo);

printf( "angle = " );
scanf("%f", &angle);

fp = fopen( "c:\\ParabolicFall.txt", "w" );

for( i = 0; i <= t; i += deltat ) {

y = Vo * sin(angle * PI / 180) * i - ( G / 2.0 ) * i * i;
x = Vo * cos(angle * PI / 180) * i;

printf( "t = %d, y = %.5f, x = %.5f\n", i, y, x );
fprintf( fp, "t=, %f, y=, %f ,x= %f\n", t, y, x );
}
fprintf( stderr, "File c:\\ParabolicFall.txt was created\n" );
fclose( fp );
return 0;
}

And how can I make the output of y always positive?Because the results are all negative.

#2
RichardM

RichardM

    Newbie

  • Members
  • PipPip
  • 21 posts
Maybe I am reading your code wrong, but I think the space is in the wrong place when you first define the file pointer variable:

FILE* fp;

I think it should be

FILE *fp;

Also, when a file is first opened, it is usually wrapped in an if condition, to check if the file was opened properly:

if ((fp = fopen( "c:\\ParabolicFall.txt", "w" )) == NULL){
  printf("Error on attempted file opening.\n");
  exit(1);
}

or something like that.

If the error message does not appear, you know the error did not occur here and must be somewhere else.

aruwin said:

. . .
how can I make the output of y always positive?Because the results are all negative.

If the computation is correct, and the results are negative--then they are negative. What would like to have done? To just negate the sign of the result? You could do that, but you'd be reversing the direction of your coordinate system.

There are a few other things in your program that could be improved.
For example,
you could define a dummy variable to hold the quantity angle * PI / 180, and take it out of the for loop. That way you are not repeatedly re-computing that same quantity.
And I have never seen float variables used as control variables in a for loop. (Does that even run?)

#3
Flying Dutchman

Flying Dutchman

    Programming God

  • Members
  • PipPipPipPipPipPipPip
  • 889 posts
  • Location:::1
Asterix (pointer) position doesn't matter in C/C++, both FILE* fp and FILE *fp are equivalent, however you must be careful when using const keyword.

@aruwin,
before you output y's value, check if it's negative or not and change value accordingly (multiply with -1 if need be).
A conclusion is where you got tired of thinking.
#define class struct    // All is public.




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users