我有一个类似于这样的字符串:
"HELLO 200 Now some random text\n now more text\t\t"
我尝试获取“HELLO”、“200”和剩余的字符串。不幸的是,该字符串可能包含“\n”和“\t”,因此我无法使用“%[^\n\t]”。
我尝试了以下方法:
char message[MESSAGE_SIZE], response[RESPONSE_SIZE];
int status;
sscanf (str, "%s %d %[^\0]", message, &status, response);
然后变量被
message = "HELLO", status = 200, response = "HELLO 200 Now some random text\n now more text\t\t"
但是响应字符串中包含 HELLO 200
(不应该有这个)。是否有一种直接使用 scanf
而不需要使用 strtok 的方法来实现这一点?
"%s %d %[^\0]"
达到了你的目标,那么你现在有什么问题? - nalzokmain.c|11|warning: no closing ']' for '%[' format [-Wformat]|
和main.c|11|warning: embedded '\0' in format [-Wformat-contains-nul]|
。第一个似乎很有趣。 - nalzoksscanf
读取格式字符串(第一个参数),直到NUL终止符('\0'
)。在"%s %d %[^\0]"
的情况下,字符串中嵌入了\0
。这解释了第二个警告。因此,sscanf
只看到"%s %d %[^"
。现在你会理解第一个警告。我不知道该字符串是否会引发未定义行为。所以,我已经提出了一个问题与此相关。 - Spikatrix