fprintf inside a for loop is not working properly - c

I am attempting to create a text file using C that will contain a table of values in Fahrenheit and their Celsius conversion.
I am able to use fprintf properly outside of the for loop but when I put it inside it does not print anything to the file. The code compiles properly but when I try to execute it completes but with exit code "-1073741819"
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
int main()
{
FILE *filePointerThree;
double myArray[100];
filePointerThree = fopen("myFileFive.txt", "w");
for(int i=0; i<=100; i++)
{
myArray[i] = (i-32)/1.8;
}
for(int j=0; j<=100; j+=5)
{
fprintf(filePointerThree, "%d degrees F \t %5.2lf degrees C\n", j, myArray[j]);
}
fclose(filePointerThree);
}

Your array needs to be larger to hold 101 values (0 through 100):
double myArray[101];
Upon further review, the code can be simplified to not require an array, as follows. A return 0; at the end of main() will ensure an exit code of 0. Minor: the math.h and stdlib.h includes are not required as fopen() and friends are defined in stdio.h.
#include <stdio.h>
int main()
{
FILE *filePointerThree;
filePointerThree = fopen("myFileFive.txt", "w");
for(int j=0; j<=100; j+=5)
{
fprintf(filePointerThree, "%d degrees F \t %5.2lf degrees C\n", j, (j-32)/1.8);
}
fclose(filePointerThree);
return 0;
}

Related

In C programming why is my printf not printing after a loop?

I need to print the sum and average of user input array. So if user inputs 2,4,6,9,10 it should print 6.
However, after the loop ended my printf is not printing anything.
Even if I put the printf inside the array it only prints out 0.
#include <stdio.h>
#include <math.h>
int main()
{
int i;
double num[6],average, sum=0, closest;
printf("Enter 6 doubles\n");
for (i=0; i<6; i++)
{
scanf("%lf",&num[i]);
sum += num[i];
}
average = sum/i;
printf("Average %d", average);
}
There are a few things you need to do in the code. You should be making sure they enter 6 numbers (in your opening post you only list 5, this will create problems). I changed the printing to use this and stripped out some variables that you don't use.
#include <stdio.h>
#include <math.h>
int main()
{
int i;
double sum = 0;
printf("Enter 6 doubles\n");
for (i = 0; i < 6; i++)
{
double value;
scanf("%lf", &value);
sum += value;
}
printf("Average = %f", sum / i);
}
Enter 6 doubles:
2 4 6 9 10 10
Average = 6.833333
This question is not a duplicate but I found the answer on StackOverflow here
The stdout stream is buffered, so will only display what's in the
buffer after it reaches a newline (or when it's told to). You have a
few options to print immediately:
Print to stderr instead using fprintf:
fprintf(stderr, "I will be printed immediately");
Flush stdout whenever you need it to using fflush:
printf("Buffered, will be flushed"); fflush(stdout); // Will now print everything in the stdout buffer
You can also disable buffering
on stdout by using setbuf:
setbuf(stdout, NULL);
Then regarding your code, here are a few remarks:
As described in man 3 printf the conversion specifier f already convert to double floating point values, so no need for a length modifer flag.
The average value is also a double so if you print it as an integer %d you will lose the real valued part, consider using %f as well.
the following proposed code:
uses a proper signature for main()
corrects the format used in the call to printf()
appends a '\n' to the format string in 'printf()' so the data is immediately output rather than after the program exits
gives 'magic' numbers (I.E. 6) meaningful names
properly checks for I/O errors and handles any such error
eliminates unneeded variables
does not include header files those contents are not used
documents why each header file is included
properly limits the scope of local variable 'i'
cleanly compiles
performs the desired functionality
and now, the proposed code:
#include <stdio.h> // printf(), scanf(), perror()
//#include <math.h>
#include <stdlib.h> // exit(), EXIT_FAILURE
#define MAX_ENTRIES 6
int main( void )
{
//int i;
// double num[6];
double num;
double average;
double sum=0.0;
// double closest;
printf("Enter %d doubles\n", MAX_ENTRIES );
for (int i=0; i< MAX_ENTRIES; i++)
{
if( scanf( "%lf", &num ) != 1 )
{
fprintf( stderr, "scanf for number failed\n" );
exit( EXIT_FAILURE );
}
sum += num;
}
average = sum / MAX_ENTRIES;
printf("Average %f\n", average);
}
a typical run of the code results in:
Enter 6 doubles
1.0
2.0
3.0
4.0
5.0
6.0
Average 3.500000

Reading decimal numbers from txt file and using them in C

I'm trying to create a program that reads three points (witch form a triangle) from b.txt file given like this:
(-3,-3) (4,-5.5) (-2,1)
Later I need to calculate triangle area (P= 15.25 for this example).
my code:
#include <stdio.h>
int main()
{
FILE *fp=fopen("b.txt","r");
int i=0;
float x[3],y[3];
char bracket,comma;
while(fscanf(fp,"%c%f%c%f%c",&bracket,&x[i],&comma,&y[i],&bracket)==5)
i++;
for(i=0;i<3;i++)
printf("%f %f\n",x[i],y[i]);
fclose(fp);
return 0;
}
As a result i am getting:
0.000000 1102137707490764237397621571846144.000000
0.000000 0.000000
0.000000 0.000000
Can anyone give me an idea how to read these numbers?
thanks in advance!
PS
I know how to read numbers (as char) with fgetc but later i cant use them for calculating triangle area.
If your line format is fixed, something like could make the job:
#include <stdio.h>
struct point {
float x;
float y;
};
int main() {
FILE *fp = fopen("b.txt", "r");
int i = 0;
struct point p[3];
char bracket, comma;
fscanf(fp, "(%f,%f) (%f,%f) (%f,%f)", &p[0].x, &p[0].y, &p[1].x, &p[1].y,
&p[2].x, &p[2].y);
for (int j = 0; j < 3; j++) {
printf("%.2f %.2f\n", p[j].x, p[j].y);
}
fclose(fp);
return 0;
}
In order to understand the code I'd recommend you take a look to fscanf docs

C, Arrays, file format not recognized

for our homework we have to compile the program we wrote in the school. I have typed it without mistakes(verified with my colleagues) and the program does not work, I am using DEV C++ and the error log says, file not recognized: File format not recognized.
I tried using integer and not double but it stays the same...I have no idea what is wrong.
#include <stdio.h>
#define VELIKOST 23
int main (void)
{
double dPolje[VELIKOST];
int iStevec,iVecje=0;
printf("Algoritem, ki določi koliko elementov podatkovnega polja imajo vrednosti vecje ali enake od 10 \r\n");
for(iStevec=0;iStevec<VELIKOST;iStevec++)
{
printf("Vnesite %i. stevilo:",iStevec=iStevec+1);
fflush(stdin);
scanf("%lf",&dPolje[iStevec]);
if(dPolje[VELIKOST]>=10)
{
iVecje++;
printf("Element dPolje [%i]=%f.",iStevec,dPolje[iStevec]);
}
printf("%i elementov polja je imelo vecje ali enako vredost 10.",iVecje);
return(0);
}
}
I'm guessing that Dev C++ doesn't support Slovenian.
Create a new file and try this code:
#include <stdio.h>
#define SIZE 23
int main(){
double dField[SIZE];
int i, larger = 0;
printf("This algorithm, determines how many data field items have values greater than or equal to 10.\n");
for (i = 0; i < SIZE; i++){
printf("Enter field number %i:", i + 1); //Note I fixed this original code had i = i + 1
//fflush(stdin); unneeded
scanf("%lf", &dField[i]);
if (dField[i] >= 10){
larger++;
printf("Field number %i = %lf", i, dField[i]);
}
} //Moved this above final output and return
printf("%i field items were greater than or equal to 10 ", larger);
return 0;
}
I expect that to work.
Either way I'd definitely change compilers. Visual Studio Community Is a great fully featured IDE.

read single-precision use double precision variable in C

I have a text file containing single precision data, such as
0.123456 0.123456 0.123456
I want to read it in C using following syntax:
FILE *myfile.
double c[4];
int i=0;
c[0]=1;
myfile=fopen(...)
for (i=1;i<=3;i++) {
fscanf(myfile, "%lf", &c[i]);
}
What I print is a huge number that is obviously wrong.
Any one can solve this problem?
Ps: I have edited my problems after I viewed the answers.
here is my more information:
#include <windows.h>
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <stdlib.h>
FILE *file_params;
int main() {
double *delx;
int i;
file_params=fopen(filename,"r");
delx = (double *) malloc ((4)*sizeof(double));
delx[0]=0;
for(i=1; i<=3; i++) fscanf(file_params, "%lf", &delx[i]);
for(i=1; i<=3; i++) printf("%lf", delx[i]);
return 0;
}
Responding to the version of code that appears as I write ...
Remove #include <windows.h>
Change filename to be the name of a file that exists
Check that file_params != NULL and delx != NULL before proceeding
Check the return value of fscanf, e.g. if ( 1 != fscanf(file_params, "%lf", &delx[i]) ) { printf("fscanf failed\n"); exit(EXIT_FAILURE); }
Change printf("%lf", to printf("%f ",
Program works.
What I print is a huge number that is obviously wrong.
Possibly you are seeing the numbers all next to each other without spaces (since you didn't printf a space) and didn't realize what you were seeing.
Array indexes start at 0. You started at 1.
for loop should be
for (i=0;i<3;i++)
fscanf(myfile,"%lf",&c[i]);
I see the following errors:
Use %lf instead of lf%.
Use &c[i] instead of &c.
In the for- loop, use,
for (i=0;i<3;i++) {
instead of
for (i=1;i<=3;i++) {
In summary,
for (i=0;i<3;i++) {
fscanf(myfile, "%lf", &c[i]);
}

Fill a matrix from a file in C

I'm trying to write a little program that read from a file. I tryied this codes from a file (random.dat) that contains the following numbers:
0.575 0.235
0.456 0.322
The code that I wrote is the following:
#include <stdio.h>
#include <stdlib.h>
#define N 2
int main (void) {
FILE *fp;
int i, j;
double x,y,data[N][N] = {{0}};
if ((fp = fopen("random.dat", "r")) == NULL ) {
printf("Error\n");
exit(EXIT_FAILURE);
}
fp = fopen("random.dat","r");
printf("\n");
for (i=0;i<N;i++){
fscanf(fp,"%lf",&x);
for(j=0;j<N;j++){
fscanf(fp,"%lf",&x);
data[i][j] = x;
printf("data[%d][%d]=%lf\n",i,j,data[i][j]);
}
}
printf("\n");
fclose(fp);
return(0);
}
Does the code is well written?
I don't understand why the terminal write:
data[0][0]=0.235000
data[0][1]=0.465000
data[1][0]=0.322000
data[1][1]=0.322000
Instead of:
data[0][0]=0.575000
data[0][1]=0.235000
data[1][0]=0.465000
data[1][1]=0.322000
Any idea? Thanks!
In this nested loop (reformatted to be easier to read):
for (i=0; i<N; i++)
{
fscanf(fp, "%lf", &x); // first fscanf
for(j=0; j<N; j++)
{
fscanf(fp, "%lf", &x); // second fscanf
data[i][j] = x;
printf("data[%d][%d]=%lf\n", i, j, data[i][j]);
}
}
You'll see that the inner loop immediately overwrites the x value read in your outer loop. That means you essentially skip reading the first number in the file entirely. Later that causes one of the inner-loop fscanf calls to fail, but since you don't check the return value, your program doesn't notice.
Just delete the first fscanf() line and you'll be set.
As an editorial aside, if you step through your program with a debugger, you'd see this problem happening immediately.
replace statements,
for (i=0;i<N;i++){
fscanf(fp,"%lf",&x);
for(j=0;j<N;j++){
fscanf(fp,"%lf",&x);
data[i][j] = x;
printf("data[%d][%d]=%lf\n",i,j,data[i][j]);
}
}
with
for (i=0;i<N;i++){
for(j=0;j<N;j++){
fscanf(fp,"%lf",&x);
data[i][j] = x;
printf("data[%d][%d]=%lf\n",i,j,data[i][j]);
}
}

Resources