【问题标题】:sscanf format string that can detect a hyphenated and non-hyphenated stringsscanf 格式字符串,可以检测带连字符和不带连字符的字符串
【发布时间】:2018-11-07 20:36:21
【问题描述】:

我正在开发一个使用 sscanf() 来检测输入的实现。 输入要么包含连字符“-”,要么不包含。字符串的长度和连字符的位置会有所不同。 例子:

"18509726-550"
"14782"

我一直在尝试提出一个格式字符串,该格式字符串对于带有连字符的字符串返回 > 0,但对于没有连字符的字符串则不然,但是我没有成功。这可能是不可能的。我也意识到有更好的方法来实现这一点,但这段代码是在我之前编写的。

代码:

// what format string will return 0 for one but not the other?
String^ pszString = "18509726-550"; // or "14782"
int nP;
char buffer[256];
char buffer1[256];
const char* pSrc = (gcnew marshal_context())->marshal_as<const char*>(pszString);
nP=sscanf(pSrc, "%[-]s", buffer, buffer1);

我尝试了几种格式字符串:

"%s-%s"
"%[0-9-]s"
"%[-]s"
"%[^-]s"

我已经翻阅了我能找到的任何 sscanf 文档,我认为单独使用 sscanf 是不可能的,但验证也有帮助。 感谢社区!

【问题讨论】:

  • 听起来你可能想要一个正则表达式。
  • 你说得对,我想要一个正则表达式,但我被 scanf 卡住了。我不认为上述是可能的,但我希望有人可能有更好的见解。

标签: c++ scanf


【解决方案1】:

[] 已经采用s 格式。 只需使用"%[^-]-%[^-]"

#include <stdio.h>

void test(const char* s)
{
    char s1[100]{}, s2[100]{};
    int n = sscanf(s, "%[^-]-%[^-]", s1, s2);
    printf("%d: %s, %s\n", n, s1, s2);
}

int main()
{
    test("18509726-550");
    test("14782");
}

打印:

2: 18509726, 550
1: 14782, 

【讨论】:

  • 感谢您的回答。但是,该格式字符串也为“14782”返回 1。我正在寻找一个识别“14782”的格式字符串没有连字符并返回0(n = 0),但同时对于像“18509726-550”这样的输入将返回> 0(n = 2)。
  • 嗯。那么只需strchr(s, '-') 不?
猜你喜欢
  • 2014-01-18
  • 1970-01-01
  • 1970-01-01
  • 2012-05-10
  • 1970-01-01
  • 2018-10-28
  • 1970-01-01
  • 2010-10-12
  • 2010-11-07
相关资源
最近更新 更多