代码之家  ›  专栏  ›  技术社区  ›  Matt

getline检查行是否为空白

  •  7
  • Matt  · 技术社区  · 15 年前

    有没有一种简单的方法来检查一行是否是空的。因此,我想检查它是否包含任何空格,如\r\n\t和空格。

    谢谢

    7 回复  |  直到 15 年前
        1
  •  20
  •   Jesse Lawson    9 年前

    你可以使用 isspace

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

    如果任何字符不是空白(即行不为空),则此函数将返回0,否则返回1。

        2
  •  3
  •   KevinOrr    8 年前

    如果一个字符串 s strspn(s, " \r\n\t") 将返回字符串的长度。因此,一个简单的检查方法是 strspn(s, " \r\n\t") == strlen(s) 但这将遍历字符串两次。您还可以编写一个简单的函数,该函数只在字符串处遍历一次:

    bool isempty(const char *s)
    {
      while (*s) {
        if (!isspace(*s))
          return false;
        s++;
      }
      return true;
    }
    
        3
  •  1
  •   Nyan    15 年前

    我不会检查“\0”,因为“\0”不是空格,循环将在此结束。

    int is_empty(const char *s) {
      while ( isspace( (unsigned char)*s) )
              s++;
      return *s == '\0' ? 1 : 0;
    }
    
        4
  •  0
  •   Benoit    15 年前

    给予 char *x=" "; 以下是我的建议:

    bool onlyspaces = true;
    for(char *y = x; *y != '\0'; ++y)
    {
        if(*y != '\n') if(*y != '\t') if(*y != '\r') if(*y != ' ') { onlyspaces = false; break; }
    }
    
        5
  •  0
  •   Rizo    15 年前

    请考虑以下示例:

    #include <iostream>
    #include <ctype.h>
    
    bool is_blank(const char* c)
    {
        while (*c)
        {
           if (!isspace(*c))
               return false;
           c++;
        }
        return false;
    }
    
    int main ()
    {
      char name[256];
    
      std::cout << "Enter your name: ";
      std::cin.getline (name,256);
      if (is_blank(name))
           std::cout << "No name was given." << std:.endl;
    
    
      return 0;
    }
    
        6
  •  0
  •   gon1332    11 年前

    我的建议是:

    int is_empty(const char *s)
    {
        while ( isspace(*s) && s++ );
        return !*s;
    }
    

    working example .

    1. 在字符串的字符上循环,并在以下情况下停止
      • 或者找到一个非空格字符,
      • 或是去拜访了努尔人。
    2. 如果字符串指针已停止,请检查字符串的内容是否为nul字符。

        7
  •  0
  •   Jonathan.    10 年前

    对于C++ 11,可以检查字符串是否为空白 std::all_of isspace (isspace检查空格、制表符、换行符、垂直制表符、进纸和回车:

    std::string str = "     ";
    std::all_of(str.begin(), str.end(), isspace); //this returns true in this case
    

    如果您真的只想检查字符空间,那么:

    std::all_of(str.begin(), str.end(), [](const char& c) { return c == ' '; });
    
    推荐文章