简体   繁体   English

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

[英]Reading a string with spaces and special character with sscanf

For a project I'm trying to read an int and a string from a string. 对于一个项目,我试图从字符串中读取一个int和一个字符串。 Here the only problem is sscanf appears to break reading an %s when it sees a space and some special character. 唯一的问题是sscanf在看到空格和某些特殊字符时似乎无法读取%s I want to print only String which is present inside special character. 我只想打印出现在特殊字符中的字符串。 Is there anyway to get around this limitation? 无论如何,要解决这个限制吗? Here is an example of what I'm trying to do: 这是我要执行的操作的一个示例:

Similar to this link with little change 此链接相似,变化不大

#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;
}

What it prints is: "cool kid >>> ram <<< is 19 years old" where I need "ram is 19 years old" . 它打印的是:我需要的“酷小子>>> ram <<<是19 岁” Is there any work around? 有什么解决办法吗?

Note: some time "cool kid" string come "coolkid" like this also. 注意:有时“ cool kid”字符串也会像这样出现“ coolkid”。

You had it, you just had your discard in the wrong place (along with a slight capitalization issue): 您拥有了它,只是将您的丢弃物放在了错误的位置(以及轻微的大写问题):

#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;
}

Output 产量

$ ./bin/sscanf_strange
ram is 19 years old

Could use sscanf(input, "%d%*[^>]>>>%199s", &age, buffer); 可以使用sscanf(input, "%d%*[^>]>>>%199s", &age, buffer); . Anything after the %s is irrelevant in scanning for age and buffer . %s之后%s内容与扫描agebuffer无关。 Not checking if all scanned can lead to trouble. 不检查所有扫描内容是否会导致故障。

Suggest checking that the entire line parsed as expected. 建议检查整个行是否按预期进行了解析。 The simple solution is to use " %n" at the end. 简单的解决方案是在末尾使用" %n" This saves the count of char scanned if scanning gets that far. 如果扫描距离太远,则可以保存扫描的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");
}

You need to look for things that aren't a > , and you need to suppress assignment on the correct bits: 您需要查找不是>东西,并且需要禁止在正确的位上赋值:

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

The length quoted in the format is one less than the number of characters available; 格式中引用的长度比可用字符数少一; it doesn't count the terminal null byte, in other words. 换句话说,它不计算终端的空字节。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM