2013-12-20 57 views
4

我需要使用fscanf來忽略所有空格並且不保留它。 我試圖使用(*)[^\n]之間的組合作爲:fscanf(file," %*[^\n]s",); 當然,它墜毀,有沒有辦法只與fscanf如何忽略fscanf中的空格()

代碼:

int funct(char* name) 
{ 
    FILE* file = OpenFileToRead(name); 
    int count=0; 
    while(!feof(file)) 
    { 
     fscanf(file," %[^\n]s"); 
     count++; 
    } 
    fclose(file); 
    return count; 
} 

解決了! 將原來的fscanf()更改爲: fscanf(file," %*[^\n]s"); 完全按照fgets()的順序讀取所有行,但沒有保留!

+1

我們可以看到崩潰的代碼嗎?我們無法解決我們看不到的問題。 –

+0

int funct(char* name) { \t FILE* file = OpenFileToRead(name); \t int count=0; \t while(!feof(file)) \t { \t \t fscanf(file," %[^\n]s"); \t \t count++; \t } \t fclose(file); \t return count; } synt

回答

2

使用fscanf格式的空格(「」)會導致它讀取並放棄輸入上的空格,直到找到非空白字符,並將該輸入中的非空白字符作爲要讀取的下一個字符。所以,你可以做這樣的事情:

fscanf(file, " "); // skip whitespace 
getc(file);  // get the non-whitespace character 
fscanf(file, " "); // skip whitespace 
getc(file);  // get the non-whitespace character 

fscanf(file, " %c %c", &char1, &char2); // read 2 non-whitespace characters, skipping any whitespace before each 

來自:

Ignoring whitepace with fscanf or fgets?

1

從人的fscanf頁:

A directive is one of the following: 
    ·  A sequence of white-space characters (space, tab, newline, etc.; 
      see isspace(3)). This directive matches any amount of white 
      space, including none, in the input. 

所以

fscanf(file, " %s\n"); 

將在讀入字符前跳過所有空格。

+0

'fscanf(file,「%s \ n」)'有問題:1)沒有目的地匹配'%s'。 2)「%s」前面的''「'不需要,因爲'」%s「'會消耗前導空白。 3)'「\ n」'做同樣不需要的空白掃描。 – chux