使用 sscanf 读取带有空格和特殊字符的字符串

Reading a string with spaces and special character with sscanf

对于一个项目,我正在尝试从字符串中读取一个 int 和一个字符串。这里唯一的问题是 sscanf 在看到 space 和一些特殊字符时似乎中断了对 %s 的读取。我只想打印特殊字符中存在的字符串。无论如何要绕过这个限制?这是我正在尝试做的一个例子:

this link类似,变化不大

#include<stdio.h>
#include<stdlib.h>

int main(int argc, char** argv) {
    int age;
    char* buffer;
    buffer = malloc(200 * sizeof(char));
    sscanf("19 cool kid >>> ram <<<", "%d %[^\t\n] >>> %*s <<<", &age, buffer);

    printf("%s is %d years old\n", buffer, age);
    return 0;
}

它打印的是:"cool kid >>> ram <<< is 19 years old",我需要"ram is 19 years old"。有什么解决办法吗?

注:有的时候"cool kid"字符串来"coolkid"也是这样。

您需要查找不属于 > 的内容,并且您需要抑制对正确位的赋值:

sscanf("19 cool kid >>> ram <<<", "%d %*[^>] >>> %199s <<<", &age, buffer);

格式中引用的长度比可用字符数少一个;换句话说,它不计算终端空字节。

你有它,你只是把你的弃牌放错了地方(还有一个小的大写问题):

#include <stdio.h>
#include <stdlib.h>

int main (void) {

    int age;
    char* buffer;
    if (!(buffer = malloc(200 * sizeof *buffer))) {
        fprintf (stderr, "error: virtual memory exhausted.\n");
        return 1;
    }
    sscanf("19 cool kid >>> ram <<<", "%d %*[^>] >>> %s <<<", &age, buffer);

    printf("%s is %d years old\n", buffer, age);

    free (buffer);

    return 0;
}

输出

$ ./bin/sscanf_strange
ram is 19 years old

可以使用 sscanf(input, "%d%*[^>]>>>%199s", &age, buffer);%s 之后的任何内容都与扫描 agebuffer 无关。不检查是否所有扫描都会导致麻烦。

建议检查整行是否按预期解析。简单的解决方案是在最后使用 " %n" 。如果扫描到那么远,这将节省 char 扫描的计数。

const char *input =  "19 cool kid >>> ram <<<";
int n = 0;
sscanf(input, "%d%[^>]>>>%*199s <<< %n", &age, buffer, &n);
if (n == 0 || input[n]) {
  puts("Bad Input");
}