understanding scanf syntax

做~自己de王妃 提交于 2021-02-11 12:47:54

问题


I have the following scanf code I am unable to understand::

char board[3][3];
int i;
for(i=0;i<3;i++) 
scanf("%s[^\n]%*c", board[i]);

Please help me understand word by word what the letters in scanf syntax mean. Thankyou.


回答1:


Read a sequence of non-whitespace characters, then "[^", newline, "]", then one more character which is not stored anywhere. I don't think this is what actually needed. You can read scanf manpage (google it) for correct syntax.

Explanation:

%s - capture a sequence of non-whitespace characters

%[ - capture a sequence of characters determined by set (ending with ']')

That's why %s[^\n] seems wrong to me. Should be %[^\n] instead.




回答2:


Afaik,

What this does is, for 3 times (inside for loop), reads a line (with %s) till it encounters a newline char (with [^\n]) and discards the last (newline) char (with %*c).

%*c

Here, "*" will tell scanf to not store the value caught by "c". i.e. the newline char.



来源:https://stackoverflow.com/questions/14027701/understanding-scanf-syntax

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!