【问题标题】:Empty whitespace in array not recgnised C++ C数组中的空白空格未被识别 C++ C
【发布时间】:2015-01-14 22:05:38
【问题描述】:

我有一个大小为 7 的 char 数组,看起来像这样......

Sean
Sam
Smith
Dave
Daniel
(empty line)
(empty line)

我基本上想将我的char 数组大小读取为5 并丢弃空行空格。

这是我的代码,但它返回 7 而不是 5

int d=0;    
for(int i=0; i<7; i++)
{
    if(strcmp(line[i]," ") == 0) // THIS LINE IS NOT RECOGNIZING THE WHITESPACE EMPTY LINES
    {
        d--;
    }
    else
    {
        d++;
    }
}

【问题讨论】:

  • 你确定这两行是" "吗?
  • 您的代码要求该行包含一个空格。如果它是 empty(即没有字符),则比较将失败。请记住空格和换行符是不同的字符。如果您希望字符串包含其中任何一个,则需要检查它们。
  • 您显然没有大小为 7 的 char 数组,因为这些名称每个都比 1 个字符长得多。另外,为什么要标记c++
  • 如果它包含一个空格,那么它不是空的!试试看:strcmp(line[i],"").
  • 恐怕也是,如果它识别出空字符串,它会返回 3,而不是 5...

标签: c++ c arrays


【解决方案1】:

您可以使用isspace() 函数并迭代您的字符串,就像这样 (source):

int is_empty(const char *s) {
  while (*s != '\0') {
    if (!isspace(*s))
      return 0;
    s++;
  }
  return 1;
}

【讨论】:

  • while (isspace((unsigned char) *s)) s++; return *s == '\0';
  • 在我问的问题的上下文中呢?行被声明为char** 数组。
  • 你可以从哪里去,只需将右指针传递给is_empty()函数。
【解决方案2】:

您的示例表明您认为“空格”是“空白”。解决您的代码示例(当行是“空格”时忽略d 的递减)

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

char *line[7] = {"Sean", "Sam", "Smith", "Dave", "Daniel", "", ""};

int main() {
    int i, d=0;    
    char *sptr;
    for(i=0; i<7; i++)  {
        sptr = strtok (line[i], "\r\n\t ");  //extract from whitespace
        if (sptr)                            // any pointer?
            if (*sptr)                       // any text?
                d++;                         // count textual lines
    }
    printf ("%d\n", d);
    return 0;
}

【讨论】:

    猜你喜欢
    • 2018-12-03
    • 2016-07-25
    • 1970-01-01
    • 1970-01-01
    • 2014-10-12
    • 2018-01-22
    • 2012-04-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多