我需要讀取代表電影放映的文本檔案中的字串行并對其進行格式化。我需要用來sscanf掃描保存的字串fgets。我的問題是如何sscanf在使用說明符的同時只讀取最多 x 個字符[^]。電影標題長度的最大長度為 44。我知道 C 有%0.*s,但我需要將它與[^]. 我試過做%0.44[^,]但無濟于事。我的代碼如下。我已經注釋掉了我認為的解決方案。
#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;
}
這列印出以下內容
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 |
我需要它
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 |
uj5u.com熱心網友回復:
sscanf(currentLine, "%[^,],C[^,],%[^,]", movieTime, movieTitle, movieRating);
其中 43 是要讀取的字符數,剩下一個用于空終止符。我假設編譯器對0.抱怨零寬度和未知轉換型別感到不滿。
uj5u.com熱心網友回復:
我知道C有
%0.*s...
不,不是的。因為,限制接受的字符數的方法是在不帶或的情況下sscanf將寬度作為十進制數字給出,如. 它必須是一個實際的數字;它不能像 in 那樣指定數字作為引數傳遞。%0."%3s"*printf
要將其與[轉換說明符一起使用,您將使用"D[^,]".
如果最大移動標題長度為 44 個字符,則應將將它們保存為字串的陣列宣告為 char movieTitle[MAX_TITLE_CHARS 1];允許終止空字符。
如果要sscanf根據符號引數化字串MAX_TITLE_CHARS,以便在值更改時進行調整,可以通過將其定義MAX_TITLE_CHARS為宏而不是const int物件來實作:
#define MAX_TITLE_CHARS 44
并定義宏以將引數轉換為字串:
// Two macros are needed due to the order of operations in macro replacement.
#define ExpandAndStringize(x) #x
#define Stringize(x) ExpandAndStringize(x)
并使用它們:
sscanf(currentline,"%[^,],%" Stringize(MAX_TITLE_CHARS) "[^,],%[^,]", movieTime, movieTitle, movieRating);
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/441819.html
