2014-12-04 36 views
2

尋找使用scanf函數讀,但我想停止閱讀,如果我遇到一個「」‘\ 0’(行)或EOF拆分scanf函數輸入數組,直到EOF

我真的不知道如何停止實現這一點。

我用

char * aBuff; 
char * bBuff; 
char * cBuff; 

//read in the first three lines and put them into char arrays 
//while (scan() != (',' || '\0' || EOF)) //was trying to put it into a while loop, wasn't sure 
scanf("%s", aBuff); 
scanf("%s", bBuff); 
scanf(%s, cBUff); 

我打算取輸入,並把它們放在不同的陣列。基本上需要輸入,直到一個或新的行,並將數據放入數組中,並繼續此過程直到文件結束。

回答

1

您可以嘗試使用scansets

scanf()的應停止在EOF,但你會想,也許做這樣的事情:

scanf("%[^,\0]", &s); 
+0

'的scanf()'將只能看到格式到''\ 0''。 '「%[^,\ 0]」將顯示爲「」%[^,「'。 – chux 2014-12-04 03:58:17

2

scanf()不是讀,直到遇到一個實用的方法',','\0'EOF。使用fgetc()

最大的問題是指定的格式爲scanf()。示例:格式爲"%[^,\0]",scanf()只能讀取"%[^,",因爲它在嵌入'\0'處停止。所以用一個無效的格式說明符 - >未定義的行爲。

size_t ReadX(char *dest, size_t size) { 
    size_t len = 0; 
    if (size) { 
    while (--size > 0) { 
     int ch = fgetc(stdin); 
     if (ch == 0 || ch == ',' || ch == EOF) break; // maybe add \n too. 
     *dest[len++] = ch; 
    } 
    *dest[len] = '\0'; 
    } 
    return len; // or maybe return the stopping ch 
} 

scanf()可以使用,如果代碼中使用的沉重:

scanf("%[\1\2\3...all_char_codes_min_char_to_max_char_except_,_and\0]%*c", &s);