如果条件太长并且包括for循环

时间:2017-05-22 14:52:14

标签: c++ arrays function loops if-statement

您好我是C ++初学者,这是我在编写函数时遇到的问题。

bool函数isData用于查看数组成员是否都是数字。通常大小将是11或9或7,所以我不想硬编码。但我不确定是否在if条件下循环工作。如果你能告诉我更简单的方法,我将非常感激。

bool isData(string temp[], int size)
{
  if(
      for (int i;i<size;i++) 
      {
        59 > +temp[i].at(0) && +temp[i].at(0) > 47 || +temp[i].at(0) == 45
      }
    )
    {
      return true;
    }
  else 
    {
      return false;
    }
}

4 个答案:

答案 0 :(得分:1)

if(boolean_expression) 你不能把表达式在 if 中返回任何内容。

bool isData(string temp[], int size)
{
    for (int i = 0; i < size; i++) 
    {
        char* p;
        long converted = strtol(temp[i], &p, 10);
        if (*p) 
        {
            // conversion failed because the input wasn't a number
            return false;
        }
    }
    return true;
}

检查一下: How to determine if a string is a number with C++?

对于double,您需要使用 strtod 而不是长时间使用double。

答案 1 :(得分:0)

for个圈不会导致truefalse,因此for中的if无法生效。

相反,运行for循环中的所有元素,如果找到非数字,则返回false。否则,请返回true

伪代码就是这样的

bool isData(String temp[], int size) {
    for(int i=0; i < size; i++) {
        if( hasOnlyDigits(temp[i]) ) { return false; }
    }
    return true;
}

hasOnlyDigits是一个可以接收string的功能,并检查它是否为有效数字。

以下是正数的单行代码。 bool hasOnlyDigits = (temp[i].find_first_not_of( "0123456789" ) == string::npos);

实现一个处理所有输入的函数,例如+.23-33--33,这是非常重要的。实现一个可以处理输入约束内输入的函数。

如果我找到一种强有力的检查方式,我会更新此答案。

答案 2 :(得分:0)

如果您可以使用C ++ 11进行编译,那么您可以使用std::stoi。类似于上面的一个答案,但更好的错误检查和确保循环遍历整个字符串数组。

bool isData(std::string temp[], int str_size)
{

    bool ret_val = false;
    size_t current_len, processed_len;
    for (int i=0; i < str_size; i++) {
        current_len = temp[i].size();
        try {
            int hidden_num = std::stoi(temp[i], &processed_len);
            std::cout << hidden_num << std::endl;
            if (processed_len == current_len) {
                ret_val = true;
                continue;
            }
        } catch (std::invalid_argument& e) {
            std::cout << "Non-integer input at index " << i << std::endl;
            ret_val = false;
            break;
        }
    }
    return ret_val;
}

答案 3 :(得分:0)

这是不必要的:

if (...some complicated boolean expression...) {
    return true;
} else {
    return false;
}

您需要做的就是:

return ...some complicated boolean expression...;