【问题标题】:Why sscanf is not handling or ignoring spaces in c++?为什么 sscanf 不处理或忽略 C++ 中的空格?
【发布时间】:2021-08-14 10:15:42
【问题描述】:

我要在sscanf 中添加以下行,但它不接受空格

char store_string[25],store_string1[10];
std::tm t={};
int store_integer,store_integer1,store_integer2;
int total_read;
           
char* buff1 = "Demo to dispay (Appname,App usage) with date (03/11/2005) with test id (87773) data added (0) total ((null))";
char* buff2 = "Demo to dispay %s with date (%d/%d/%d) with test id (%d) data added (%d) total ((%d))";
            
total_read = sscanf(buff1, buff2 , store_string,  &t.tm_mon,
&t.tm_mday,
&t.tm_year,
&store_integer,&store_integer1,&store_integer2);

   

输出:

如果 buff1 有显示 (Appname,Appusage) 它工作正常

但如果 buff1 显示 (Appname,App usage) 则会失败

【问题讨论】:

  • std::istringstreamstd::getline() 或其他文本提取方法有什么问题?
  • 如果您对sscanf 有疑问,为什么要使用如此复杂的示例?为什么不是一个没有空格的简单字符串,一个有空格的字符串呢?为什么需要在问题中引入int变量、日期等?
  • 我需要用 sscanf 实现输出。我需要知道我们如何在单行中实现这一点,而不是创建 while 循环或 forloop。 sscanf 的简单限制。
  • 我知道你想使用sscanf。如果您想学习如何正确使用某些东西,请使用一个较小的示例,在该示例中您尝试从一个字符串或两个由空格分隔的字符串中获取输入。它将问题集中在那个问题上。所有这些带有日期、整数的额外垃圾,它们在实际问题中毫无用处,除了使代码混乱。

标签: c++ visual-studio c++11 scanf


【解决方案1】:

为什么 sscanf 不处理或忽略 c++ 中的空格?

sscanf 应该如何分隔单词/标记? 从其文档中:

["%s"] 匹配一系列非空白字符(字符串)

我认为您根本无法使用 sscanf 或单行来处理此问题。 您可以使用 std::string::find_first_ofstd::string::substr 来做到这一点

编辑:

如果你习惯了正则表达式,std::regex_match 可能是最灵活和可读的方式。

【讨论】:

    猜你喜欢
    • 2016-07-09
    • 1970-01-01
    • 2023-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多