I have two-dimensional arrays which contain the input from a file. I want to assign integers and strings from the array to different variables; the integer is set correctly, but the string is not working.
the input is like:
(1,2) apple 2 3 north
but all these information are inside:
char data[MAX_LINES][MAX_LEN];
I am trying to use sscanf to assign values:
sscanf(data[i],"(%d,%d) %8s %d %d %8s",&x,&y,type,&age,&hun,direction);
Code structure by ignoring unrelated code
FILE *in_file = fopen(fileName,"r");
char data[MAX_LINES][MAX_LEN];
int x,y,age,hun;
char type[10];
char deriction[20];
if(! in_file){
printf("cannot read file\n");
exit(1);
}
int line=0;
while(!feof(in_file) && !ferror(in_file)){
if(fgets(data[line],MAX_LEN,in_file) !=NULL ){
char *check = strtok(data[line],d);
line ;
}
}
fclose(in_file);
for(int i = 9; i<14;i ){
sscanf(data[i],"(%d,%d) %8s %d %d %8s",&x,&y,type,&age,&hun,deriction);
}
CodePudding user response:
#include <stdio.h>
int main(){
//Data:
char data[1][100] = {"(1,2) apple 2 3 north"};
//Define variables:
int x, y, age, hun;
char type[10], direction[10];
sscanf(data[0], "(%d,%d) %s %d %d %s", &x, &y, type, &age, &hun, direction);
//Check by printing it out:
printf("(%d,%d) %s %d %d %s\n", x, y, type, age, hun, direction);
printf("x: %d\ny: %d\ntype: %s\nage: %d\nhun: %d\ndirection: %s", x, y, type, age, hun, direction);
//Success:
return 0;
}
If this doesn't work, then the problem might be the data in your array, data
.
CodePudding user response:
You have the line char *check = strtok(data[line],d);
. You've not shown what d
is, but unless it is a string with no characters in common with the input line, strtok()
just mangled your stored data, zapping whatever is the first character from d
with a null byte. That means your sscanf()
will fail because it isn't looking at the whole line. If, perchance, you have const char d[] = "\r\n";
or equivalent, this ceases to be relevant, beyond pointing out that you should show enough code to reproduce the problem.