【问题标题】:How to set sscanf() to ignore characters at start of string?如何设置 sscanf() 以忽略字符串开头的字符?
【发布时间】:2013-01-01 15:08:24
【问题描述】:

我有一个字符串如下

 char row[]="11/12/1999 foo:bar some data..... ms:12123343 hot:32";

我想使用 sscanf 将 'ms' val 插入到 int 变量中。 但我不知道如何配置 ssscanf 以忽略行中的第一个数据。 我尝试打击,但没有完成这项工作。

int i;
sscanf(row,".*ms:%d",i);

【问题讨论】:

  • sscanf(strstr(row, "ms:") + 3, "%d", &i);
  • 如果你知道只有一个冒号,你也可以sscanf(row, "%*[^:]:%d", &i);
  • 不,还有其他冒号
  • @herzlshemuelian 试试我的答案,我还给了一个链接打开第二个答案
  • @GrijeshChauhan 谢谢我写了关于你的解决方案的评论。

标签: c++ c scanf


【解决方案1】:

我认为,与其使用 sscanf() 忽略数据,最好的办法是使用另一个函数来获取所需的字符串部分。

我建议strstr()。 例如

#include <stdio.h>
#include <string.h>

int main(void) {
    char row[] = "11/12/1999 foo:54654 some data..... ms:12123343 hot:32";
    char *ms;
    int i;

    ms = strstr(row, "ms:");
    if (ms == NULL) /* error: no "ms:" in row */;
    if (sscanf(ms + 3, "%d", &i) != 1) /* error: invalid data */;
    printf("ms value is %d.\n", i);
    return 0;
}

你可以看到code running at ideone

【讨论】:

【解决方案2】:

在 shell 中使用了小丑,但 sscanf 不会以这种方式处理 * 字符。

7.21.6.2 fscanf 函数
— 一个可选的赋值抑制字符 *.

有几种解决方案。例如:

#include <stdio.h>
#include <string.h>

char *pend = strrchr(row, ':');
sscanf(pend, ":%d", &i);

您还可以使用来自scanfstrstr 的扫描集。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-08-29
    • 2020-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-01
    • 2016-01-14
    相关资源
    最近更新 更多