I am working on a C program for an introductory course and am currently stuck.
The program computes the approximate value of cos(x) via Taylor series expansion.
The catch is that it reads input from a dat. file which consists of a certain number of rows of three numbers each, containing information that is meant to be processed.
For instance, the dat. file might be:
5
1 -1 6
2 1 .0001
2 1.5 2
...
The first number of each row determines which method to compute cos(x), the second number determines the value of x, etc.
I process this file as a multidimensional array:
int array[64][64], m;
FILE *ifp
ifp = fopen("cos_input.dat", "r");
i = 0;
fscanf(ifp, %d\n", &m); //takes the first value into int m
while (fscanf(ifp, "%d %d %d\n", &array[i][0], &array[i][1], &array[i][2]) == 3) {
i++;
}
^This code (I think) puts the input data file into a m x 3 array.
Now I need to manipulate the elements of the array and then write them to another output dat. file, which takes the form, for example:
x = 1
x = 2
x = 3
x = 4
...
My notion to accomplish this is to first, implement my other functions with the values stored in the multi-dimensional array, which I believe I can do, just declaring each value of my array and throwing them into the computational blender that is my other functions. (e.g., power(array[3][2], array[1][2]);) Then I have to print them to a dat. file, which I have no clue how to do.
This is because I am very sketchy on my knowledge of pointers and the fprintf/fscanf functions.
When I am writing my final data it will consist of some loop which will spit out one value per line. What is the code to use in order to print this to cos_output.dat? Must I create a new pointer expression 'ofp' similar to how I created 'ifp' in order to open the input file and implement it with scanf?
This is my first and only step I can come up with so far.
FILE *ofp; //output file pointer
ofp = fopen("cos_output.dat", "w"); //the final output data file
//.... how to print? T_T
Thanks, your help is very much appreciated!
(http://ece15.ucsd.edu/Labs/lab3.pdf) <- Link to the assignment (Problem 1) only if my explanations are unclear.
You can print to a file by doing something like
FILE *ofp; //output file pointer
ofp = fopen("cos_output.dat", "w"); //the final output data file
for (i = 0; i < 5; i++) {
fprintf(ofp, "x = %d\n", i);
}
This will generate a cos_output.dat file contains
x = 0
x = 1
x = 2
x = 3
x = 4
You can modify this fprintf() statement to output whatever you want. See fprintf(3) for further details.
Related
I'm trying to store 10 decimal numbers from a text file into an array. My problem is that it is skipping several numbers until it reaches the end of line.
I debugged the program by printing out the number of cycles the program took for reaching the end of the file, and resulted 10. And it is the correct value of how many numbers there are in the file. But when I display the element values of the array, only 5 numbers are there. When I compare the stored numbers with the text file numbers, It results that several numbers are being skipped.
Here is my code below :
#include <stdio.h>
#include <stdlib.h>
main(void)
{
FILE *inp; /* pointer to input file */
double item;
int cnt=0,y,d,i;
double array[300],swap;
/* Prepare files for input */
inp = fopen("C:/Users/infile.txt", "r");
/* Read each item */
while ( (fscanf(inp, "%lf", &item) == 1) && (!feof(inp)) ) {
array[cnt] = item;
cnt++;
}
for (int i = 0; i < cnt; i++)
{
printf("%lf\n",array[i]);
i++;
}
printf("%d",cnt);
fclose(inp); /* Close the files */
return (0);
}
-In the text file there are 10 double numbers ranging from 0 to 101 (ex 15.12563)
-The value for the cycle times of the while loop is 10 (cnt reaches 10)
-My code only stores 5 numbers instead of 10, which is skipping the rest 5 numbers, but it says it has reached the last value at line 10.
These are the values in the text file:
21.388000
12.372628
21.961366
85.616285
30.123001
30.271053
70.733982
35.867327
48.339462
82.459009
If I left some key information about my concern please ask. Thanks
It is very simple problem
You store the values correctly. The error is in your printing cycle.
You increment the i two times. Please delete the i++; from second cycle.
I tested it, and it works well
This is some code I used to read and store lines from a text file into an "expressions" array:
//create array for going through the file
char lines[128];
//create array for storing expressions
char **expressions = malloc(128*sizeof(char*));
FILE *file = fopen(argv[1],"r");
int count = 0;
while (fgets(lines,128,file)){
expressions[count] = lines;
printf("expressions[%d] is %s\n",count,expressions[count]);
count++;
}
for (int i = 0; i<count; i++){
printf("%s",expressions[i]);
}
And this is the text this code is trying to read:
f = g + h - 42;
g = 12 + 23;
My issue here is that while it appears to go through the file properly (count matches the number of lines), the final print loop prints the last line g = 12 + 23 twice instead of the two distinct lines. Why is this occuring and what can I do to fix this issue?
Each time you read a line, you store it in the lines character array, and then you save the address of that array in the next space of expressions. If you look at the values stored in expressions you'll find that they are all the same.
If you want to keep a copy of each line, you're going to have to have space to store a copy of each line. If you have a maximum number of lines which you're going to deal with, you can allocate that memory in the program. Otherwise you're going to have to start using dynamic memory allocation.
Let's work on 100 lines maximum, with each line no longer than 127 characters (as above):
char expressions[100][128];
int count = 0;
while (fgets(lines,128,file)) {
strcpy(expressions[count], lines);
printf("expressions[%d] is %s\n",count,expressions[count]);
count++;
if (count == 100)
break;
}
The text file contains 52 lines that are in the format:
A .013420
B .000191
C .011222
...
I want to ignore the letters and I need to extract the values from the file and store the first 26 in one array which I named freqOne[] and store the last 26 values in another array named freqTwo[]. I will later use these values for calculations.
here is my attempt:
#include <stdio.h>
#include <stdlib.h>
int main (){
FILE *input1;
/*char freqOne[26]; i use these arrays for attempt 1
char freqTwo[26];*/
double freqOne[26];
double freqTwo[26];
input1 = fopen("test8.txt", "r");
if(input1 == NULL){
perror("test8.txt");
exit(EXIT_FAILURE);
}
/* attempt one: all the values print out correctly but idk how to use them :(*/
/*while(fgets(freqOne, sizeof(freqOne), input1)){
printf("%s", freqOne);
}
while(fgets(freqTwo, sizeof(freqTwo), input1)){
printf("%s", freqTwo);
}
*/
/*fclose(input1); */
int h;
int i;
/* another attempt i made, this one prints out the a large negative number for every element :(*/
for(i=0; i<26; i++){
fscanf(input1,"%lf", &freqOne[i]);
printf("%lf\n", freqOne[i]);
}
for(h=0;h<26; h++){
fscanf(input1,"%lf", &freqTwo[h]);
printf("%lf\n", freqTwo[h]);
}
fclose(input1);
/*a = (freqOne[0]-freqTwo[0])*(freqOne[0]-freqTwo[0]);
printf("%lf", a);*/
}
In my first attempt, i was able to print out all the values correctly, but I am not sure how to use them. I printed them out as strings, but when I try to print them out as %lf, it gave me 0's for every value.
In my second attempt, I did some googling and found that I should try the fscanf function, but this did not work for either and a large negative number was printed out for every value. I am pretty stuck right now and out of ideas.
So OP can close this post:
To ignore the A,B,C, etc., use assignment suppression '*'
// fscanf(input1,"%lf", &freqOne[i]);
fscanf(input1,"%*s %lf", &freqOne[i]);
Always a good idea to check I/O function results:
if (fscanf(input1,"%*s %lf", &freqOne[i]) != 1) Handle_Unexpected_Input();
so I am trying to make a matrix reader that will take a text file that contains only data for a NxN matrix such as:
10 9 8 7
6 5 4 3
2 1 0 1
Read the test file into a dynamic multidimensional array. The program will not have headers, so it will need to read the entire file in order to obtain # of rows/cols.
Once I have all the data in my array I then will be able to manipulate how I want (i.e. swapping columns/rows, reversing order, etc).
At this point I am just trying to get my program to simply output the array as it appears in the test file once the entire matrix has been read in.
Here is what I have written so far:
#include <stdio.h>
#include <stdlib.h>
int main() {
int n;
int i=0;
int j=0;
scanf("%d", &n);
int **array;
array = malloc(n * sizeof(int *));
if(array == NULL) {
printf("Out of memory\n");
exit(1);
}
for(i = 0; i < n; i++) {
array[i] = malloc(n * sizeof(int));
if(array[i] == NULL) {
printf("Out of memory\n");
exit(1);
}
}
for(i = 0; i < n; i++) {
for(j = 0; j < n; j++) {
int k;
scanf("%d", &k);
array[i][j] = k;
printf("%d ", array[i][j]);
}
}
}
And running this gives me output:
9 8 7 6 5 4 3 2 1 0 1 1 1 1 1 1 1 1 1 1 1 1... repeating 1's...
I am not sure what is wrong with my code I have been staring at it for a solid hour and have made 0 progress.
Because my output prints out about 100 different ints I feel that my problem lies in my printing loops, and I feel like it has something to do with int n, but I am not sure how to deal with this.
Any help with be greatly appreciated! Thanks.
The issue is as follows: The first number that is obtained from your file is 10 and that is being stored inside the int n close towards the beginning. That value defines the width and height of your multi-dimensional array, your matrix. You then ask for further values from that file, exactly 10 * 10 many times.
The file, however, only has 4 * 3 - 1 = 11 numbers left in it. It provides them all, right into the int k. Those values get stored inside your matrix, printed. After the 11th (or 12th if you count the first 10) the scanf starts failing. As it fails, it returns the value EOF == -1 but you do not recognize that.
Failure leaves the k as it is, although I am not sure whether it is guaranteed to remain what it previously was, since as far as I know, k could very well have another memory location allocated for itself with each cycle, since (again) as far as I know it gets cleared at the end of each loop. In your case, it does keep its value, luckily I would say, and that gets stored/printed.
In the end, you should have exactly 100 numbers printed, because of that 10 at the very beginning.
Even if you had an additional 4 at the very beginning, you'd end up with a matrix that has a wild last line with all 1s.
If you want to have a 3 by 4 matrix in your hands, consider making your file as the following example:
3 4
10 9 8 7
6 5 4 3
2 1 0 1
Then read the first value into an int n and then second one into an int m. Make first memory allocation with malloc( n * sizeof * array );, then the secondary allocations with malloc( m * sizeof ** array );.
You could also alternatively omit reading anything, deduce how many rows and columns your matrix should have by reading the amount of new-line '\n' occurrences in your file (plus one), as well as amount of numbers there are on a single line.
Edit:
Okay, let's show this you could also part: This is just an example, I'll be using a pair of scanfs for counting both the amount of lines that have at least one number inside and amount of numbers on a single line.
...
int n = 0;
int m = 0;
int discardable;
while ( scanf( "%d", &discardable ) == 1 ) {
// as long as a number has been successfully read
n++;
if ( scanf( "%*[^\n]" ) != 0 )
// discard everything until a '\n'
// and if you fail to encounter a '\n' anywhere until the file ends...
break;
}
// rewind back to the beginning of the file
rewind ( stdin );
while ( scanf( "%d", &discardable ) == 1 ) {
// as long as a number has been successfully read
m++;
if ( scanf( "%*[ \t]" ) != 0 || stdin->_ptr[0] == '\n' )
// discard every ' ' or '\t'
// if you rather get carried until the end of file, break
// else, if the upcoming character is '\n', again, break
break;
}
rewind ( stdin );
...
There you have it, n and m here should be storing the height and width of the matrix you should have, respectively.
This is just a way to do it, I can see why many could potentially just hate this, because I have made use of the FILE structure, and referred to _ptr, but whatever. I personally would prefer this any day over carrying a temporary character array and read from it.
My code requires me to open up a file.
the first line of the file contains 2 integers between 1 and 1000.
I must read these 2 numbers, use them to create a 2D array corresponding to those numbers
(e.g. 50,200 is - array[50][200]).
After i have created this array, i have to read the rest of the file and store the data (which is set up in a grid of the dimensions of the 2 numbers).
What is the best way to go about this. I thought about doing a getline and then doing a for loop to append the chars to row then column and then converting to int, but my compiler kept coming up with errors.
Is the file binary or text? If binary, use fread, it will let you read the raw bytes easily. if its text use fscanf
Assuming the input is always of this form (a little unclear):
2,4
aaaa
b b
... then an approach would be to read in the dimensions of your matrix (number of rows, number of columns) and then follow that up by reading each element of the matrix one character at a time. It would be something along the lines of this:
int rows = getchar();
// Skip ','.
getchar();
int cols = getchar();
int arr[ rows ][ cols ];
int r = 0;
int c = 0;
for ( int byte = getchar(); byte != EOF; byte = getchar(), c++ ) {
if ( c == cols ) {
c = 0;
r++;
}
arr[ r ][ c ] = byte;
}
... and you would need to pipe the input file to your program as follows:
./program.out < input.txt
Remark: This is tailored to your specific problem-set, it would not work if: the input is not guaranteed to populate the entire array, the input is a bad size, overflow of dimensions, etc. (many issues) - so be sure to account for those.