Click here to Skip to main content
15,896,434 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
The program is the start of a program that will read a file consisting of two columns of
data. This is my current data text in which these values will be outputted and rearranged.
1 2
3 4
37 45
36 90
2 32
4 56
12 72
65 38
12 98
34 45
6 45
78 29

the rows and columns are printed out with the columns switched. Upon running my code I receive 0s in both columns. I think my issue is data1 and data2 variables need to be replaced with the appropriate array location, but I'm stuck on how to solve this.
Here's my current code; I cannot make any modifications to the code except within the while loop; which I think is fine partially but has an issue correctly reading my text values. Here's my code; 
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv)
{
	
	if (argc != 2 ) {
		
		printf("%s filename\n", argv[0]);
		exit(0);
	}
	FILE *fp = fopen(argv[1], "r");
	if (fp == NULL) 
	{
		perror("Could not open file");
		exit(0);
	}
	int num_rows = 0;
	int num_columns = 2;
	int *column1 = malloc(10 * sizeof(int));
	int *column2 = malloc(10 * sizeof(int));
	int data1;
	int data2;
	int retval;
	while (1) 
	{   
		int retval = fscanf(fp,"%d %d\n", &data1,&data2); 
		if(retval==EOF) 
				break; 
			num_rows++;
			if(num_rows%10==0)
				column1 = realloc(column1, (num_rows + 10)*sizeof(int));
				
					
	}
	int i;
	for (i=0; i<num_rows; i++) {
		printf("%d ", column2[i]);
		printf("%d\n", column1[i]);
	}
	
}


What I have tried:

I've tried setting a char*filename = argv[1] but this has not worked.
Posted
Updated 12-Mar-21 12:54pm

1 solution

Try this :
C++
while (1)
{
    int retval = fscanf(fp,"%d %d\n", &data1,&data2);
    if(retval==EOF)
        break;

    column1[ num_rows ] = data1;
    column2[ num_rows ] = data2;
    num_rows++;

    if(num_rows%10==0)
    {
       column1 = realloc( column1, (num_rows + 10)*sizeof(int) );
       column2 = realloc( column2, (num_rows + 10)*sizeof(int) );
    }
}
int i;
for( i=0; i<num_rows; i++ )
{
    printf( "%d %d\n", column1[ i ], column2[ i ] );
}
remember to release the memory you have allocated.
 
Share this answer
 
Comments
Rick York 12-Mar-21 18:55pm    
Note - swap column1 and column2 on the printf if want them to be reversed.
Member 15084336 12-Mar-21 19:22pm    
Thanks, I made some changes to my identations and it fixed it also. Appreciate the help.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900