织梦CMS - 轻松建站从此开始!

abg欧博官网|登陆|游戏|

当前位置: abg欧博官网|登陆|游戏| > abg欧博 > 文章页

What does %[^\n] mean in C?

时间:2025-08-23 13:04来源: 作者:admin 点击: 0 次
scanf("%[^\n]",line); is a problematic way to read a line. It is worse than gets(). C defines line as: A text stream is an ordered sequenc

scanf("%[^\n]",line); is a problematic way to read a line. It is worse than gets().

C defines line as:

A text stream is an ordered sequence of characters composed into lines, each line consisting of zero or more characters plus a terminating new-line character. Whether the last line requires a terminating new-line character is implementation-defined.

The scanf("%[^\n]", line) has the specifier "%[^\n]". It scans for unlimited number of characters that match the scan-set ^\n *1. If none are read, the specifier fails and scanf() returns with line unaltered. If at least one character is read, all matching characters are read and saved and a null character is appended.

*1 The scan-set ^\n implies all character that are not (due to the '^') '\n'.

'\n' is not read

scanf("%[^\n]",.... fails to read a new line character '\n'. It remains in stdin. The entire line is not read.

Buffer overflow

The below leads to undefined behavior (UB) should more than 99 characters get read.

char line[100]; scanf("%[^\n]",line); // buffer overflow possible

Does nothing on empty line

When the line consists of only "\n", scanf("%[^\n]",line); returns a 0 without setting line[] - no null character is appended. This can readily lead to undefined behavior should subsequent code use an uninitialized line[] as a string. The '\n' remains in stdin.

Failure to check the return value

scanf("%[^\n]",line); assumes input succeeded. Better code would check the scanf() return value.

Recommendation

Do not use scanf() and instead use fgets() to read a line of input.

#define EXPECTED_INPUT_LENGTH_MAX 49 char line[EXPECTED_INPUT_LENGTH_MAX + 1 + 1 + 1]; // \n + \0 + extra to detect overly long lines if (fgets(line, sizeof line, stdin)) { size_t len = strlen(line); // Lop off potential trailing \n if desired. if (len > 0 && line[len-1] == '\n') { line[--len] = '\0'; } if (len > EXPECTED_INPUT_LENGTH_MAX) { // Handle error // Usually includes reading rest of line if \n not found. }

The fgets() approach has it limitations too. e.g. (reading embedded null characters).

Handling user input, possible hostile, is challenging.

(责任编辑:)
------分隔线----------------------------
发表评论
请自觉遵守互联网相关的政策法规,严禁发布色情、暴力、反动的言论。
评价:
表情:
用户名: 验证码:
发布者资料
查看详细资料 发送留言 加为好友 用户等级: 注册时间:2025-08-23 17:08 最后登录:2025-08-23 17:08
栏目列表
推荐内容