You need an ampersand &object[i][0]
in both sscanf
and printf
. Also, the compiler might complain about type error, in which case you will also need to cast: (char *)&object[i][0]
Reading from file into 2D char array
Question
What I'm trying to do is simple in concept, but I can't quite get it to work in practice.
I have a file that I'm trying to read from, there's 3 columns. The first and second are integer columns while the third contains a string.
I'm taking the contents of this file and writing them into a series of arrays. My problem lies in the character array, which is two dimensional.
#include <stdio.h>
#include <stdlib.h>
#include <strings.h>
#define NUMBER 128 //Maxmimum number of items/lines in file.
#define BUFFER 120 //Buffer length.
#define LENGTH 32 //Maximum length of lines in file.
//------------------------Global Variables. ---------------------------------------------
int iterations=0; //Will count number of times the calculation function is called.
int weight[NUMBER];
int value[NUMBER];
char object[NUMBER][LENGTH];
//------------------------Main. ---------------------------------------------------------
int main(void)
{
FILE *fp; //File pointer.
char buffer[120]; //Temporary storage
int result;
int i,j=0;
int weight[NUMBER];
int value[NUMBER];
char object[NUMBER][LENGTH];
fp=fopen("knapsack.data","r");
if(NULL==fp){
printf("Error opening file. \n");
exit(0);
}
//Print the file.
printf("Weight \t Value \t Object \n");
for(i=0;i<=NUMBER;i++){
while(NULL != fgets(buffer, 120, fp)){
result=sscanf(buffer, "%d %d %s", &weight[i], &value[i], object[i][0]);
printf("%d \t %d \t %s \n", weight[i], value[i], object[i][0]);
}
}
for(j=0;j<4;j++){
printf(" String i equals %s \n", object[j]);
}
fclose(fp);
}
The problem I'm encountering is that upon printing, I find that the contents of the strings column is (null) like so:
Weight Value Object
1 10 (null)
2 25 (null)
5 40 (null)
7 100 (null)
Should I be trying to parse the file in another way, or is it just something small I'm missing? Thanks in advance.
Solution
OTHER TIPS
Either use &object[i][0] or object[i] (they can both be used interchangeably, they mean the same thing with c strings)
As far as your output and why it's not printing successfully, it has to do with the way you are reading in the data from the file. You are using a while loop when you should be using an if statement inside the while loop to check for the iterations reaching NUMBER of times run. Something like this should work:
i = 0;
while(NULL != fgets(buffer, 120, fp))
{
if(i < NUMBER)
{
result = sscanf(buffer, "%d %d %s", &weight[i], &value[i], object[i]);
printf("%d \t %d \t %s \n", weight[i], value[i], object[i]);
i++;
}
}
I tested this out with your code and a sample knapsack.data file that I created and it works just fine on both parts, without the & by the way :)