检查getline获取的行是否为空白行

10

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

谢谢


但是 isspace() 的返回值取决于安装的 c 语言环境。因此,它可能会对换行符或制表符返回 false。 - Suba
9个回答

25
你可以使用 isspace 函数在循环中检查所有字符是否为空格。
int is_empty(const char *s) {
  while (*s != '\0') {
    if (!isspace((unsigned char)*s))
      return 0;
    s++;
  }
  return 1;
}

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


3
isspace函数的参数应该强制转换为unsigned char(is*系列函数不喜欢负数输入,而且char可能是有符号的):isspace((unsigned char)*s) - pmg
@pmg 如果“the is* functions”不喜欢负输入,那么为什么这些函数有类型为int的参数? - pmor
因为C11 7.4这样说--“......如果参数是int类型,那么它的值应该可以表示为无符号字符或等于宏EOF的值。如果参数具有任何其他值,则行为未定义”。 - pmg

3
如果字符串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;
}

1

我不会检查'\0',因为'\0'不是空格,循环会在那里结束。

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

1
*s == '\0' ? 1 : 0 could be simplified to *s == '\0' - Will Da Silva

0

给定一个 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; }
}

0

考虑以下示例:

#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;
}

1
str*cc 哪个是它? :-) - pmg
@pmg:只有 str 是错误的。*cc 的值,所以没问题!但还是谢谢你! - Rizo

0

可以使用 strspn 一次完成(只需一个布尔表达式):

char *s;
...
( s[ strspn(s, " \r\n\t") ] == '\0' )

0
你可以使用sscanf查找长度为1的非空格字符串。如果sscanf只找到空格,则会返回-1。
char test_string[] = " \t\r\n";    // 'blank' example string to be tested
char dummy_string[2];   // holds the first char if it exists
bool isStringOnlyWhiteSpace = (-1 == sscanf(test_string, "%1s", dummy_string));

0

我的建议是:

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

带有工作示例

  1. 循环遍历字符串的字符,并在以下情况停止:
    • 找到一个非空格字符,
    • 或访问了nul字符。
  2. 在字符串指针停止的位置,检查字符串的内容是否为nul字符。

就复杂性而言,它是线性的O(n),其中n是输入字符串的大小。


0

对于 C++11,您可以使用 std::all_ofisspace 来检查字符串是否为空格(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 == ' '; });

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接