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
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;
}
Here's my code
#include <stdio.h>
#include <stdlib.h>
int main ()
{
int x = 0;
int y = 0;
float a[5][2]; //array
float b[3][2]; //array
float c[2][2]; //array
FILE *fr;
//int c;
float power;
char unit[5];
//int N; //Number of sensors
float TI; //Time interval
//char M; //Midpoint
//char T; //Trapezoid
//int SR; //Sample Rate
fr = fopen("sensor_0.txt","r");
/*fr = fopen("sensor_1.txt","r");
fr = fopen("sensor_2.txt","r");
*/
//----------------------------------------------------------------------------------------------------------------------------
printf("The contents of %s file are :\n", "sensor_0.txt");
while ( !feof( fr ) )
{
fscanf(fr, "%f %f %s",&TI, &power, unit);
//printf("%f, %f \n", TI,power); //print
a[x][y] = TI;
a[x][++y]= power;
x++;
y = 0;
}
fclose(fr);
//----------------------------------------------------------------------------------------------------------------------------
printf("%s", "hello");
return 0;
}
Why isn't my string printing out anything after the while loop?
If I uncomment the same line inside the while loop, it prints properly. I've also tried just adding simple printf("hello") yet nothing seems to work after the while loop.
Edit - minor formatting.
output should just be
700 25.18752608 mW
710 26.83002734 mW
720 26.85955414 mW
730 23.63045233 mW
I suspect the file has 5 lines, not 4.
Your test of !feof() fails because you have not hit the end of file yet when you try to read the 6th line. fscanf fails but you do not test the return value. So you store TI and power beyond the end of the 2D array, invoking undefined behavior.
Changing the loading code this way should fix the problem:
while (x < 5 && fscanf(fr, "%f %f %4s", &TI, &power, unit) == 3) {
a[x][0] = TI;
a[x][1] = power;
x++;
}
if (x != 5) {
printf("incomplete input\n");
}
Doing what chqrlie suggested worked.
"instead of while ( !feof( fr ) ) that is incorrect, use while (fscanf(fr, "%f %f %4s",&TI, &power, unit) == 3)"
I want to read a .dat file whose first line consists of a float and all consecutive lines are "int * int" or "int / int" and print or return whether the float is a result each division or multiplication.
I am very unpleased with the results that I am getting. My experience is limited to only a couple of hours doing C. Therefore I have no idea what is missing for the program to do what the code is looking like it would do.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int countlines(FILE* f){
int nLines = -1;
char xLine[10];
while(fgets(xLine,10,f)!=NULL){
nLines+=1;
}
return nLines;
}
int main(){
FILE * fPointer = fopen("test.dat", "r");
float dpFloat;
char oprnd[10];
int frstInt;
int scndInt;
//get float from first line
fscanf(fPointer, "%f", &dpFloat);
//count amount of lines below float
int amtLines = countlines(fPointer);
//loop through the other lines and get
int i;
for (i = 0; i < amtLines; i++){
fscanf(fPointer, "%d %s %d", &frstInt, oprnd, &scndInt);
//checking what has been read
printf("%d. %d %s %d\n", i, frstInt, oprnd, scndInt);
//print 1 if firstline float is quot/prod of consecutive line/s
//else 0
if (strcmp(oprnd,"*") ==1) printf("%i\n", (frstInt*scndInt)==dpFloat);
if (strcmp(oprnd,"/") ==1) printf("%i\n", (frstInt/scndInt)==dpFloat);
}
fclose(fPointer);
return 0;
}
Problem 1: strcmp returns 0 when its arguments are equal, not 1.
Problem 2: frstInt/scndInt will truncate the result. Fix it by adding 1.0* to the expression.
The lines
if (strcmp(oprnd,"*") ==1) printf("%i\n", (frstInt*scndInt)==dpFloat);
if (strcmp(oprnd,"/") ==1) printf("%i\n", (frstInt/scndInt)==dpFloat);
need to be
if (strcmp(oprnd,"*") == 0) printf("%i\n", (frstInt*scndInt)==dpFloat);
if (strcmp(oprnd,"/") == 0) printf("%i\n", (1.0*frstInt/scndInt)==dpFloat);
// ^^^ ^^^
Please be aware of the pitfalls of comparing floating point numbers. It's best to compare them within a tolerance. See Comparing floating point numbers in C for some helpful tips.
I'm trying to calculate the size of the file . The process I've followed is to read the file and store it in an array and calculate its size. However,I really don't know ... I tried n number of ways..I've to pass this size as an attribute to the frequency function.along with the name of the array.
#include <stdio.h>
#include<conio.h>
void frequency (int theArray [ ], int ??????, int x)
{
int count = 0;
int u;
for (u = 0; u < ??????; u++)
{
if ( theArray[u]==x)
{
count = count + 1 ;
/*printf("\n%d",theArray[u]);*/
}
else
{
count = count ;
}
}
printf ("\nThe frequency of %d in your array is %d ",x,count);
}
void main()
{
FILE*file = fopen("num.txt","r");
int integers[100];
int i=0;
int r = 0;
int num;
int theArray[100];
int there[100];
int n;
int g;
int x;
while(fscanf(file,"%d",&num)>0)
{
integers[i]=num;
printf("\n%d",(integers[i]));
there[r] = integers[i];
i++;
}
//printf("%d",there[r]);
//printf("\n%d",file);
//fclose(file);
printf ("\n OK, Thanks! Now What Number Do You Want To Search For Frequency In Your Array? ");
scanf("\n%d", &x);/*Stores Number To Search For Frequency*/
frequency(integers,????????,x);
getch();
fclose(file);
}
?????? is the size of the integer array from where i read the file and stored it.
I could not find a way to calculate the size of the array into which i copied my file. My idea is to calculate the frequency of a number in that file and calculate the probability of it's occurrence and thereby calculating entropy..Suggestions please!
I don't know why you are initializing so many variables and some of them with awkward names like ??????.
Your main problem is that the call to function should be
frequency(integers, i, x);
Your code with the awkward irrelevant parts removed will look like
#include <stdio.h>
#include<conio.h>
void frequency (int theArray [ ], int number, int x)
{
int count = 0;
int u;
for (u = 0; u < number; u++)
{
if ( theArray[u]==x)
count++;
}
printf ("\nThe frequency of %d in your array is %d ",x,count);
}
void main()
{
FILE*file = fopen("num.txt","r");
int integers[100];
int i=0;
int num;
int x;
while(fscanf(file,"%d",&num)>0)
{
integers[i]=num;
printf("\n%d",integers[i]);
i++;
}
printf ("\n OK, Thanks! Now What Number Do You Want To Search For Frequency In Your Array? ");
scanf(" %d", &x);/*Stores Number To Search For Frequency*/
frequency(integers,i,x);
getch();
fclose(file);
}
There are a lot of parts of this code that don't make sense, but I assume it is your debugging trying to figure out what is wrong. The answer to your specific question is:
For each value read from the file you set integers[i] to the value and then increment i. Thus i is the count of items in integers. You then pass integers to frequency(), so i should be passed to the second parameter as the count.
Note that if there are more than 100 values in the file, you will over index integers and cause unpredictable behavior.
To calculate length of array:
int len= sizeof(arr)/sizeof(arr[0]);
It will give length of array without looping.
I just started with C programming and I'm making a program that calculates a specific amount of Fibonacci numbers. It works fine, except that I get the error "Segmentation fault (core dumped)". What's wrong with my code?
#include <stdio.h>
int main() {
int max;
long long int fiNum[] = {1, 1};
printf("How many numbers do you want to get? ");
scanf("%d", &max);
int i = 1;
long long int x;
while ( i < max ) {
x = fiNum[i] + fiNum[i-1];
printf("%lld ", x);
i++;
fiNum[i] = x;
}
printf("\nDone!\n");
return 0;
}
When I ask for let's say 10 numbers the output is:
2 3 5 8 13 21 34 55 89
Done!
Segmentation fault (core dumped)
I'm using Linux (Ubuntu) btw.
Thanks in advance.
You're going out-of-bound accessing the static array fileNum for which only 2 elements are allocated.
Hence you're the victim of undefined behavior. Anything could happen but in your case it's crashing at the end.
If you want to store the generated fibonacci numbers then better dynamically allocate the array after getting the input from the user.
since you said that you are a C beginner, here are some tips :) :
#include <stdio.h>
int main () {
/*When you program in C, try to declare all your variables at the begining of the code*/
int max;
long long int fiNum[]={1,1}; /* malloc! It is allways the solution and the problem too, but stick with malloc
something like fiNum = malloc (n*sizeof(long int)); I never malloc a long int
so just verify if its like this...
*/
long long int x;
int i=1; /*Try to only initializes loop variables inside the loop, like: for(i=1; i< max; i++){}*/
printf("How many numbers do you want to get? ");
scanf("%d",&max);
printf("max: %d\n", max);
while (i<max) { /*Here you could use a for loop*/
printf("i value: %d\n",i);
x=fiNum[i]+fiNum[i-1];
printf("%lld ",x);
i++;
fiNum[i]=x;
}
printf("\nDone!\n");
return 0;
}
Obs.: I had run your code in my linux and because invalid access to vector position it didn't print all the numbers that I asked.
And now, the fixed code:
#include <stdio.h>
#include <stdlib.h>
int main () {
int max;
int i;
long long int *fiNum;
printf("How many numbers do you want to get? ");
scanf("%d",&max);
fiNum = malloc(max*sizeof(long int));
fiNum[0] = 1;
fiNum[1] = 1;
for (i = 1; i < max-1; i++)
fiNum[i+1] = fiNum[i]+fiNum[i-1];
for (i = 0; i < max; i++)
printf("fi[%d]: %d\n", i+1, fiNum[i]);
printf ("\nDone!\n");
return 0;
}