2014-12-04 47 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);