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)"
Related
Can someone help me. My code is printing an extra number
It's suppose to work like this:
if is N=38
then it's suppose to print
32.0
33.8
35.6
37.4
but mine prints
32.0
33.8
35.6
37.4
39.2
how do i get rid of the last number. I'm still a beginner so i'm quite bad at this
#include<stdio.h>
int main(){
int i, n;
float f;
printf("toogoo oruulna uu: ");
scanf("%d", &n);
i=0;
while (f<=n){
f = (9.0/5.0 * i) + 32;
printf("%.1f\n", f);
i++;
}
return 0;
}
A quick fix
while (1){
f = (9.0/5.0 * i) + 32;
if(f>n) // Move condition to after calculation
break;
printf("%.1f\n", f);
i++;
}
This will also solve the bug that you're using f before it's initialized.
You can do this:
#include<stdio.h>
int main(){
int i, n;
float f;
printf("toogoo oruulna uu: ");
scanf("%d", &n);
i=0;
f=0;
while (f<=(n-1)){
f = (9.0/5.0 * i) + 32;
printf("%.1f\n", f);
i++;
}
return 0;
}
Look while (f<=(n-1)) , the while loop will stop 1 iteration earlier and make sure you are setting the f variable with a value before you use it!
I'm wondering how to make the compiler repeat itself if the user presses a random button at the end. But if the user presses "0" the compiler exits.
My code:
#include<stdio.h>
#include<stdlib.h>
#include <math.h>
#include <float.h>
struct mystruct
{
float startnummer;
float hoppnummer;
float svarighetsgrad;
float domarpoangs[7];
};
int main(void)
{
struct mystruct data;
float max = 0;
float min = FLT_MAX;
float sum = 0;
float avg = 0;
int i = 0;
float resultat = 0;
printf("Startnummer: \n");
scanf_s("%f", &data.startnummer);
printf("Hoppnummer:\n");
scanf_s("%f", &data.hoppnummer);
printf("Svarighetsgrad:\n");
scanf_s("%f", &data.svarighetsgrad);
for (i = 0; i < 7; i++)
{
printf("domarpoang %d\n", i + 1);
float f;
if (scanf_s("%f", &f) == 1)
{
if (f < min) min = f;
if (f > max) max = f;
data.domarpoangs[i] = f;
}
else
{
printf("error parsing float\n");
exit(0);
}
}
system("cls");
printf("Startnummer: %.1f \n", data.startnummer);
printf("Hoppnummer: %.1f\n", data.hoppnummer);
printf("Svarighetsgrad: %.1f\n", data.svarighetsgrad);
for (i = 0; i < 7; i++)
{
printf("Domarpoang %d: %.1f\n", (i + 1), data.domarpoangs[i]);
}
for (i = 0; i < 7; i++)
{
sum += data.domarpoangs[i];
}
sum = sum - (max + min);
avg = sum/5;
resultat = avg * 3 * data.svarighetsgrad;
printf("Hoppoang:%.2f \n", resultat);
printf("Tryck tangent for nytt hopp!");
getchar();
getchar();
return 0;
}
*If the user presses random button, the compiler repeat itself from the beginning
*If the user presses 0, the compiler exits.
Any help is appreciated, thank you.
This answer puts a loop around the body of your main() code, taking care to re-initialise some of the variables for the next iteration.
There are many SO questions about getting keyboard input and clearing the debris. I know of no simple standard ways of testing for keyboard input such as kbhit(), for taking a single key input such as getch() or for flushing the input. Even getchar() is horrible - it won't return until you have pressed "Enter" which it leaves in the input buffer. This has resulted in many SO answers with impenetrable (to me) formats for scanf() to flush the input, or testing if (getchar() == EOF) - which does not respond to the "Enter" key.
So I have put a simple wrapper around the main() code, which terminates when '0' is entered followed by a control char (because fgets() appends the newline) or terminator. This removes the need to clean up the input - except in the case where the user inputs some silly typing. GIGO!
#include <stdio.h>
#include <float.h>
#define BUFFSIZE 10
struct mystruct {
float startnummer;
float hoppnummer;
float svarighetsgrad;
float domarpoangs[7];
};
int main(void)
{
char kbuff [BUFFSIZE+1];
struct mystruct data;
float max;
float min;
float sum;
float avg;
int i;
float resultat;
do {
max = 0; // initialise for each loop
min = FLT_MAX;
sum = 0;
printf ("Body of your main loop\n");
fgets(kbuff, BUFFSIZE, stdin);
} while (kbuff[0] != '0' || kbuff[1] >= ' ');
return 0;
}
I'm trying to get input in an array, I expect input like the following.
5 (Number of the second dimensions in the array)
2 (Number of the first dimensions in the array)
So we get an array deeln[2][5] in this example. I try to get it with the following code:
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
bool isinarray(int val, int *arr, int size){
int countimp;
for (countimp=0; countimp < size; countimp++) {
if (arr[countimp] == val)
return true;
}
return false;
}
int main(void){
int k, d, ci, cj, ck, ta;
//get input
scanf("%i", &k);
scanf("%i", &d);
int deeln[d][k], temp[k];
for(ci = 0; ci < d; ci++){
printf("d= %i, ci= %i \n", d, ci);
scanf("%s", temp);
for(cj = 0; cj < k; cj++){
deeln[ci][cj] = temp[cj*2]-'0';
}
}
//loop while.
}
But i've got a problem, whenever i try to input, the program runs automaticly without getting any input when it loops around the third scanf for the 2nd or 3rd time. So then i'm not able to input anything.
What to do? Has it something to do with pointers or am i using scanf wrong?
UPDATE:
If I enter a printf after printf("cj is nu %i \n", cj); then the output also just came after the loop was going its own way. and not before i should give more input, using the third scanf.
The solution of my question was quite easy. I found it after thinking of my input. The problem was that in the input, as described, there were spaces. Somehow scanf can't handle with spaces, unless you use some other syntax. But my solution is to just use fgets instead of scanf where I wanted to get the input. So the new and working code is as follows:
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
bool isinarray(int val, int *arr, int size){
int countimp = 0;
for (countimp=0; countimp < size; countimp++) {
if (arr[countimp] == val)
return true;
}
return false;
}
int main(void){
int t, k = 0, d = 0, ci = 0, cj = 0, ta = 0;
//get input
scanf("%i", &k);
scanf("%i", &d);
char temp[20];
int deeln[d][k];
memset(deeln, 0 , sizeof(deeln));
memset(temp, 0 , sizeof(temp));
for(ci = 0; ci < d; ci++){
fgets(temp, 20, stdin);
for(cj = 0; cj < k; cj++){
ta = cj*2;
deeln[ci][cj] = temp[ta]-'0';
}
}
//loop while.
return 1;
}
Thanks for helping everbody, even though we all didn't came to this. But I hope it will help others!
Two places to look:
1)
cj = 0;//initialize cj before using here
scanf("%i", &temp[cj]);//temp is both an array, and an int. Fix your format specifier,
//and use an index operator - temp[?] (not sure I am using the right index)
2)
deeln[ci][cj] = temp[cj*2]-'0'; //fix your logic here (array index will be exceeded)
An example of working code...
int main(void){
int k, d, ci, cj, ck, ta;
//get input
scanf("%i", &k);
scanf("%i", &d);
int deeln[d][k], temp[k];
for(ci = 0; ci < d; ci++){
printf("d= %i, ci= %i \n", d, ci);
for(cj = 0; cj < k; cj++){
if(scanf("%i", &temp[cj]) != EOF)
{
deeln[ci][cj] = temp[cj]-'0';
}
else deeln[ci][cj] = -1;
}
}
getchar();
//loop while.
}
you can play with the index of temp[cj] to make it what you actually want, but I assume you are intending to read from stdin, then populate deeln[][] with that value, for each scanf.
If you want to parse a string containing spaces and digets, "1 3 8 5 3", you could use strtok()
But your code as it is is not reading a string in, it is reading integers.
This is not perfect, you will have to do some debug, but will illustrate strtok(). You have to enter spaces between each digit after indices are selected: i.e.:
3
3
4 6 8
2 4 7
1 2 8
int main(void){
int k, d, ci, cj, ck, ta;
//get input
scanf("%i", &k);
scanf("%i", &d);
char inStr[d][k*5]; //space for up to k 3 digit numbers with 1 space each
char *buf=0;
int deeln[d][k], temp[k];
for(ci = 0; ci < d; ci++){
printf("d= %i, ci= %i \n", d, ci);
if(scanf("%s ", inStr[ci]) != EOF)
{
buf = strtok(inStr[ci], " ");
cj = 0;
while(buf && (cj < k))
{
deeln[ci][cj] = atoi(buf);
cj++;
}
}
}
//getchar();waits for user input, pauses execution
}
I have a program which needs to read data from a file but I do not want to give the files name and want to take the data into my command file, like nbody < input ???
The code I have been provided (called nbody.c) is a simplified version of an N-body simulation that illustrates the above theory. The code can be compiled, linked and an executable file called nbody created by using the following command.
gcc –lm nbody.c –o nbody
To run the executable an example data input file called input is provided as a starting point. The serial code can be executed using the following command which takes a few seconds to run to completion.
nbody < input
my program is;
#include <stdio.h>
#include <math.h>
int m = 1000;
void simulate(int m, int n, double delt, double eps, double x[], double y[], double z[],
int iter, double xn[], double yn[], double zn[]);
int main(int argc, char *argv[])
{
double x[m], y[m], z[m], xn[m], yn[m], zn[m];
double delt, eps, resultant;
int i, n, iter;
char ch, file_name[25];
FILE *fp, *ofp;
//file_name=argv[0];
//char *mode = "r";
printf("Enter the name of file you wish to see\n"); //instead of this, i wanted it reads automatically, like taking data from the file and calculate it.
gets(file_name);
fp = fopen(file_name, "r");
rewind(fp);
printf("The contents of %s file are : \n", file_name);
fscanf(fp,"%d %lf %lf", &n, &delt, &eps);
printf("n = %d, delta t = %lf and tolerance = %lf \n",n, delt, eps);
fclose(fp);
//while(ch=fgets(fp)!=EOF){
//printf("enter n, delta t and tolerance\n");
//scanf("%d %lf %lf", &n, &delt, &eps);
//printf("%c",ch)
//printf("enter n, delta t and tolerance\n");
//scanf("%d %lf %lf", &n, &delt, &eps);
simulate(m, n, delt, eps, x, y, z, iter, xn, yn, zn);
printf("n = %d, delta t = %lf and tolerance = %lf \n",n, delt, eps);
for (i=1; i <= n; i++) {
resultant = sqrt(x[i]*x[i]+y[i]*y[i]+z[i]*z[i]);
printf("%-5.7lf %-5.7lf %-5.7lf %-5.7lf\n", x[i], y[i], z[i], resultant);
}
return 0;
}
void simulate(int m, int n, double delt, double eps, double x[], double y[], double z[],
int iter, double xn[], double yn[], double zn[])
{
/*
Author C.Ierotheou
Aug 2009
Copyright University of Greenwich
routine to crudely simulate body-body interactions (inefficient method)
*/
double zero = 0.0, one = 1.0, twopi = 6.2831853071795864769252866;
int i, itest, j;
double aux,auy,delt2,delt3,eps2,fx,fy,fz,ftx,fty,ftz,step;
// return if n<5
if (n < 5) return;
//initialization
iter = 0;
delt2 = 0.5*delt*delt;
delt3 = delt2*delt2;
eps2 = eps*eps;
//initial distribution of points
auy = zero;
itest=n+1;
j = n+2;
fx = (double)(n);
x[1] = zero;
y[1] = zero;
z[1] = one;
for (i=2; i <= n; i++) {
step = (double)(i+i-j)/fx;
auy = fmod(auy+3.6/sqrt(itest*(one-step*step)),twopi);
aux = sin(auy);
x[i] = aux*step;
y[i] = aux*sin(acos(step));
z[i] = cos(auy);
}
// main iteration loop
Mainloop:
iter=iter+1;
itest=0;
for (i=1; i <= n; i++) {
// total sum of force vectors
fx=zero;
fy=zero;
fz=zero;
for (j=1; j<=n ; j++) {
if (j != i) {
aux=pow(x[i]-x[j],2.0)+pow(y[i]-y[j],2.0)+pow(z[i]-z[j],2.0);
aux=aux*sqrt(aux);
fx=fx+(x[i]-x[j])/aux;
fy=fy+(y[i]-y[j])/aux;
fz=fz+(z[i]-z[j])/aux;
}
}
// tangential component of force
aux=x[i]*fx+y[i]*fy+z[i]*fz;
ftx=fx-x[i]*aux;
fty=fy-y[i]*aux;
ftz=fz-z[i]*aux;
aux=ftx*ftx+fty*fty+ftz*ftz;
if (aux > eps2) {
itest=1;
aux=sqrt(one-aux*delt3);
xn[i]=x[i]*aux+ftx*delt2;
yn[i]=y[i]*aux+fty*delt2;
zn[i]=z[i]*aux+ftz*delt2;
}
}
for (i=1; i <= n; i++) {
x[i]=xn[i];
y[i]=yn[i];
z[i]=zn[i];
}
if (itest == 1) goto Mainloop;
}
You asked:
In C, how to read data from file using x
You don't do that in C. That kind of functionality is provided by your shell/console/run time environment.
If you have a program x that can read its input from stdin, and you have a file y that contains the input appropriate for x, you use:
x < y
from the shell.
Update
I think I know where your problem might be. You have:
char ch, file_name[25];
FILE *fp, *ofp;
//file_name=argv[0];
//char *mode = "r";
printf("Enter the name of file you wish to see\n"); //instead of this, i wanted it reads automatically, like taking data from the file and calculate it.
gets(file_name);
fp = fopen(file_name, "r");
Instead of using gets to read the name of your input file, you would like to pass the name of the input file from the command line. I hope I am on the right track on this.
In that case, you need to use:
char* file_name = argv[1]; // argv[0] is the program name
// argv[1] is the first argument to the program
Then, you can just use:
x y
where x is your program and y contains the input data needed by x.
That's some really terrible code. But if you must use it, try changing main to this:
int main()
{
double x[m], y[m], z[m], xn[m], yn[m], zn[m];
double delt, eps, resultant;
int i, n, iter;
printf("The contents of %s file are : \n", file_name);
while (scanf("%d %lf %lf", &n, &delt, &eps) == 3)
printf("n = %d, delta t = %lf and tolerance = %lf \n",n, delt, eps);
simulate(m, n, delt, eps, x, y, z, iter, xn, yn, zn);
printf("n = %d, delta t = %lf and tolerance = %lf \n",n, delt, eps);
for (i=1; i <= n; i++) {
resultant = sqrt(x[i]*x[i]+y[i]*y[i]+z[i]*z[i]);
printf("%-5.7lf %-5.7lf %-5.7lf %-5.7lf\n", x[i], y[i], z[i], resultant);
}
return 0;
}
I am trying to do what's been done here Read co-ordinates from a txt files using C Program . The data that I am trying to input is in this format:
f 10 20 21
f 8 15 11
. . . .
f 11 12 25
The only difference in my point structure is that I have a an extra char to store the letter in the first column (which may or may not be the letter f). I guess im either declaring my char wrong, or I'm calling it in printf incorrectly. Either way, I only get the first line read and then my program terminates. Any ideas ?
Here is my MWE below
#define FILEPATHtri "/pathto/grid1DT.txt"
#define FILEPATHorg "/pathto/grid1.txt"
#define MAX 4000
#include <stdio.h>
#include <stdlib.h>
#include "math.h"
typedef struct
{
float x;
float y;
float z;
char t[1];
}Point;
int main(void) {
Point *points = malloc( MAX * sizeof (Point) ) ;
FILE *fp ;
fp = fopen( FILEPATHtri,"r");
int i = 0;
while(fscanf(fp, "%s %f %f %f ", points[i].t, &points[i].x, &points[i].y, &points[i].z ) == 4 )
{
i++;
}
fclose(fp);
int n;
for (n=0; n<=i; n++){
printf("%c %2.5f %2.5f %2.5f \n", points[i].t, points[n].x, points[n].y, points[n].z ); }
printf("There are i = %i points in the file \n And I have read n = %i points ",i,n);
return 0;
}
Since there's only 1 char in there, not a string just use a single char in your code:
char t;
}Point;
Then when you read it in:
while(fscanf(fp, "%c %f %f %f ", &points[i].t, &points[i].x, &points[i].y, &points[i].z ) == 4 )
{
I'll note that having an array of 1 char, at the end of a structure, sets you up for the struct hack which might not have been your intentions... A good reason to use just char t instead of char t[1]
Also this line:
for (n=0; n<=i; n++){
Should be
for (n=0; n<i; n++){
One last note... if you wanted to print the character out that you read in the prints at the bottom, you should be using n:
// note your previous code was points[i].t
printf("%c %f %f %f \n", points[n].t, points[n].x, points[n].y, points[n].z ); }
Check this
while(fscanf(fp, "%c %f %f %f ", points[i].t, &points[i].x, &points[i].y, &points[i].z ) == 4 )
{
i++;
}
fclose(fp);
int n;
for (n=0; n<i; n++){
printf("%c %2.5f %2.5f %2.5f \n", points[n].t, points[n].x, points[n].y, points[n].z ); }
printf("There are i = %i points in the file \n And I have read n = %i points ",i,n);
getch();
return 0;
}
modification are since only a single character is read %s modified to %c also in printf its not points[i].t its points[n].t . Also the limit checking in for loop is also corrected to n<i