I have a file that I’m trying to read and fill variables with. The file consists of this:
0\ttake a nap\n
1\tstudy heap-based priority queue\n
101\treview trees for Midterm 2\n
3\tdo assignment 7\n
This may be hard to read, but you can see that there is an integer to begin with, followed by a tab, a string after that, followed by a newline. I need to take the integer and put that into a variable, detect the tab, and put the string following the tab into a variable, detect the newline, take the two variables and create a node with the information, and then start over again on the next line. After hours of scouring the internet, this is what I’ve come up with:
char activity[SIZE];
char position[SIZE];
char line[100];
FILE *infile;
char *inname = "todo.txt";
int i = 0;
infile = fopen(inname, "r");
if (!infile) {
printf("Couldn't open %s for reading\n");
return 0;
}
while(i < 100 && fgets(line, sizeof(line), infile) != NULL){
sscanf(line, "%s\t%s", position, activity);
printf("%s\n", position);
printf("%s\n", activity);
i++;
}
When running this test code on the txt file above, I get this as a result:
0
take
1
study
101
review
3
do
So, it looks to me like it’s getting the first number alright (as a string) and putting it into the variable, seeing the tab, and grabbing the first sequence after the tab and stopping there after putting it into the other variable. How do I rectify this situation?
You can try changing the
sscanf:The
%sspecifier stops when it encounters blanks. That’s why it only reads study instead of study heap-based priority queue. The%[^\n]tells it: "read until newline". Another issue: you should test the value returned bysscanfto make sure it filled the required number of objects.You could also read the first integer as an integer, changing
positiontointand using%dinstead of%s.EDIT
To make myself clear, what I was suggesting was: