Reputation: 1
I am new to programming so I apologize if I mess up on anything.
So I am trying to scan a file with multiple lines of numbers and put them into a two dimensional array. I've tried looking at other questions relating to this and nothing has worked so far.
So I have tried using nested loops to scan the array and put the numbers inside but nothing seems to happen. Inside the txt file is as follows:
0 7 9 4 0 0 8 0 4 5 0 1 0 2 4 0 0 0 1 6 2 8 6 0 0 1 1 1 1 0 8 5 6 8 0 7 0 5 1 0 0 0 1 3 8 1 0 1Every 12th number is a new line.
#include <stdio.h>
#define BUF_SIZE 12
#define ROW 4
#define COL 12
void
barcodeArray(int barcode[ROW][COL])
{
char buffer[BUF_SIZE];
FILE* f = fopen("q5_input.txt","r");
if(f == NULL)
{
printf("no such file.");
}
for(int k = 0; k < ROW; k++)
{
for(int j = 0; j < COL; j++)
{
fscanf(f, "%1d", &barcode[k][j]);
printf("%ls", &barcode[k][j]);
}
}
fclose(f);
}
int
main(void)
{
int barcode[ROW][COL];
barcodeArray;
}
The printf inside the for loops is just reading back the numbers as it inputs the numbers in the array. As the code is it compiles but does nothing.
Upvotes: 0
Views: 63
Reputation: 2670
Try this way. I think using freopen() is easier and hassle free. It enables you to use same I/O functions that you use for console I/O operations.
#include <stdio.h>
#define BUF_SIZE 12
#define ROW 4
#define COL 12
void barcodeArray()
{
int barcode[ROW][COL];//This can be declared inside the function.
char buffer[BUF_SIZE];
FILE* f=freopen("q5_input.txt","r",stdin);
if(f == NULL)
{
printf("no such file.\n");
return;
}
for(int k = 0; k < ROW; k++)
{
for(int j = 0; j < COL; j++)
{
scanf("%d",&barcode[k][j]);
printf("%d ",barcode[k][j]);
}
printf("\n");
}
fclose(f);
}
int main(void)
{
barcodeArray();
}
Additionally if you want to output it in a file you can do the following in the main function:
int main(void)
{
freopen("out.txt","w",stdout);
barcodeArray();
}
Upvotes: 1
Reputation: 395
You must call your function with argument barcodeArray(barcode);
Edit : If you are not sure of the size of the array you can take a look at dynamically allocated variables. This is an important part of C programming
Upvotes: 1