I need to read lines of strings in a text file that represent movie showings and format them. I need to use sscanf
to scan the string saved by fgets
. My problem is how do I make sscanf
only read upto x amount of characters while also using [^]
specifier. Movie title lengths have a max length of 44. I know C has %0.*s
but I need to use it in combination with [^]
. I tried doing %0.44[^,]
but to no avail. My code is below. I have commented out what I though would be the solution.
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
int main(void) {
const int MAX_TITLE_CHARS = 44; // Maximum length of movie titles
const int LINE_LIMIT = 100; // Maximum length of each line in the text file
char line[LINE_LIMIT];
char inputFileName[25];
FILE *file;
file = fopen("D:\\movies.csv", "r");
char currentLine[LINE_LIMIT];
char movieTitle[MAX_TITLE_CHARS];
char movieTime[5];
char movieRating[5];
fgets(currentLine, LINE_LIMIT, file);
while(!feof(file)){
// sscanf(currentLine, "%[^,],%0.44[^,],%[^,]", movieTime, movieTitle, movieRating);
sscanf(currentLine, "%[^,],%[^,],%[^,]", movieTime, movieTitle, movieRating);
printf("%-44s |\n", movieTitle);
fgets(currentLine, LINE_LIMIT, file);
}
return 0;
}
This prints out the following
Wonders of the World |
Wonders of the World |
Journey to Space |
Buffalo Bill And The Indians or Sitting Bull's History Lesson |
Buffalo Bill And The Indians or Sitting Bull's History Lesson |
Buffalo Bill And The Indians or Sitting Bull's History Lesson |
Adventure of Lewis and Clark |
Adventure of Lewis and Clark |
Halloween |
I need to it be
Wonders of the World |
Wonders of the World |
Journey to Space |
Buffalo Bill And The Indians or Sitting Bull |
Buffalo Bill And The Indians or Sitting Bull |
Buffalo Bill And The Indians or Sitting Bull |
Adventure of Lewis and Clark |
Adventure of Lewis and Clark |
Halloween |