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]);
}
Related
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;
}
I create it a program that asks for raw and columns after that asks you to put numbers to the dimensional array. This arrays inputs to a file. When i open the file i can't see the array.
#include <stdio.h>
#include <stdlib.h>
#include <curses.h>
int main () {
FILE *fp;
int n,m;
int i,j;
float b;
char filename[100];
int getfloat(float *);
printf("Number of rows\n");
scanf("%d",&n);
printf("Number of colums\n");
scanf("%d",&m);
float s[n][m];
for (i=1;i<=n;i++)
{
for (j=1;j<=m;++j)
{
printf("Insert number %d",i);
printf(",%d\n", j);
scanf("%f",&b);
s[i][j]=b;
}
}
printf("Enter file name \n");
scanf("%s", filename);
// ****print file****
fp=fopen(filename,"w+");
if(fp!=NULL)
{
fputs(s,fp);
fprintf("%c",s);
}
fclose(fp);
return 0;
the only thing i see is this
If you want a list of numbers, probably in some kind of grid in the file, then at the minimum you want a loop such as the following:
for (int i=0; i<n; ++i)
{
for (int j=0; j<m; ++j)
{
fprintf(fp, "%f ", s[i][j]);
}
fprintf(fp, "\n");
}
See fprintf for documentation on the format specifiers; you'll probably want to tweak that to get better-looking values.
Also, again, note that arrays start from 0. Your initial read loop skips the very first element, and writes past the end of the actual array.
fprintf("%c", s); and fputs does not print out the contents of the array, it prints out the location stored in the array's pointer and tries to interpret it as a char. What you would need to print out the proper values is to loop through each value and use fprintf with each float value, using s[i][j] similar to how you initialized it.
The way you initialized the array is also off, as arrays begin at 0, not 1. Currently your for loop does not ever access s[0][0] or s[1][0] and so on. Your for loops should have i initialized to 0, and have the condition be i < n instead of i<=n.
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
probably another dumb error but I really can't wrap my head around this.
I'm writing a basic polynomials class, and my program suddenly crashes upon input of a couple of ints.. I tried searching for a solution but I couldn't find one :/
The code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "Homework.h"
#include "Fraction.h"
int main()
{
//Input from user
int degree, i;
printf("Insert the degree of the polynomomial: \n");
scanf("%d", °ree);
//Get the coefficcients
struct fraction *bucket = malloc((sizeof(struct fraction))*(degree + 1));
int num;
unsigned int den;
for(i = 0; i < degree + 1; i++)
{
num = 0;
den = 1;
printf("Insert the coefficcient of degree %d, first num and afterwards
the den \n", i);
printf("Numerator:\n");
if(scanf("%d", &num) != 1)
printf("Input error\n");
printf("Denominator:\n");
if(scanf("%u", &den) != 1)
printf("Input error\n");
//struct fraction temp = {num, den};
//memcpy(&bucket[0], &temp, sizeof(struct fraction));
}
//Check insertion
printf("Test\n");
//print_fraction(bucket[0]);
}
The program exits even before printing "Test", and to input I am using input number + enter key.
Thanks very much for any help!
Proof it compiles
Your code seems to be working fine.
The only changes i've made in order to compile it was to comment out the line where you are using malloc, and also brought your print statement on one line.
If you are using a newer version of Visual Studio then it will give you issues when using the scanf function. You either have to use scanf_s or disable the warning with this line at the top:
#pragma warning(disable: 4996)
Hope this helps.
I'm relatively new to C programming, its my 6th week in class so far i haven't had any major issues. I just cant figure out were i'm going wrong with my current assignment and its due in just a couple hours. Here is what i have so far. i'm using visual studio 2012.
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char textChar;
int textLenght = 0;
int asciiArray[128] = {0};
int i;
int main()
{
printf("Enter a line of text: ");
scanf("%d", &textChar);
while ((textChar = getchar())!= '\n') {
textLenght++;
asciiArray[textChar]++;
}
printf("\nFREQUENCY TABLE\n");
printf("---------------\n");
printf("Char Count %% of Total\n");
printf("---- ----- ----------\n");
printf(" ALL %5d %9.2f%%\n", textLenght,( textLenght * 100.0 ) / textLenght );
for (i = 0; i < 128; i++)
if( asciiArray[textChar] != 0 )
printf("%c %d %9.2f%% \n",i+ "0",asciiArray[textChar]);
getchar();
getchar();
return 0;
}
Now i know there is a problem within my for loop because its not displaying, I'm just not sure if there are other problems besides that. Any help is greatly appreciated thanks in advance.
This line is not right.
scanf("%d", &textChar);
It's not clear to me what you are trying to accomplish with this line.
When you use %d as the format specifier, the function will try to read an integer and store it at the given address. Since type of textChar is not int, you are going to run into undefined behavior right away.
Instead of using getchar, which is not a standard C library function, you should use fgetc(stdin).
fgetc() returns an int. Make sure to change the type of textChar to int.
Change the lines:
printf("Enter a line of text: ");
scanf("%d", &textChar);
while ((textChar = getchar())!= '\n') {
textLenght++;
asciiArray[textChar]++;
}
to
printf("Enter a line of text: ");
while ((textChar = fgetc(stdin))!= '\n') {
textLenght++;
asciiArray[textChar]++;
}
I would remove the last two calls to getchar(). They don't seem to serve any purpose.