c++ - if 字符串验证循环的问题

标签 c++ string debugging if-statement nested

<分区>

我正在研究一个验证 if 循环,它在开始和结束时检查管道并确保有 32 个有效字符(有效字符是 : 和 |)

我想知道为什么我的程序没有正确读取 32 个字符输入的 if 语句。这是我目前所拥有的。

void checkitout(string validate)
{
   string check;
   check = validate;

   if ((check.length() == 31) && 
       (check.substr(0,1) == "|") && 
       (check.substr(31,1) == "|"))
   { 
     cout << "is this running?";

     for (int i = 0; i < 31; i++)
     {   
       cout << "for loop running";

       if (!(check.substr(i, 1) == ":") || !(check.substr(i, 1) == "|"))
       {
         cout << "Please enter acceptable barcode.";
         return;
       }
     }
   }
   else
   {
     cout << "else Please enter acceptable barcode";
   }
}

我是新手,但我认为我走在正确的轨道上。 cout 将测试循环是否正常工作。它直接进入 else 状态。这是一个示例输入

||:|:::|:|:||:::::||:|::|:::|||

一如既往,我们非常感谢任何关于如何更好地做到这一点的想法。

最佳答案

您的字符串的长度为 32,因此 if 条件为假,因为 check.length() == 31。 此外,循环中的 if 条件需要“&&”而不是“||”,因为您希望它既不是“|”也不是“:”是 Not Acceptable 条形码。

更改以粗体标记。

void checkitout(string validate)
{
   string check;
   check = validate;
   string one = check.substr(4,1);
   cout << (check.substr(4,1) == one) << endl;

   if ((check.length() == **32**) &&
       (check.substr(0,1) == "|") &&
       (check.substr(31,1) == "|"))
   {
     cout << "is this running?";

     for (int i = 0; i < 31; i++)
     {
       cout << "for loop running";

       if (!(check.substr(i, 1) == ":") **&&** !(check.substr(i, 1) == "|"))
       {
         cout << "Please enter acceptable barcode.";
         return;
       }
     }
   }
   else
   {
     cout << "else Please enter acceptable barcode";
   }
}

关于c++ - if 字符串验证循环的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26752789/

相关文章:

c++ - QFileDialog::getOpenFileName 调试时崩溃,显然是由项目名称引起的?

flutter - 如何检查 Flutter 应用程序是否正在调试中运行?

c++ - uniform_int_distribution 的问题

C - 大串中的最大串

string - 如何在没有迭代的情况下在 Dart 中将 list<String> 转换为 String?

string - 如何向 Ansible 变量添加新行 "\n"字符

c# - 将自定义调试信息传递给 Microsoft bot 框架模拟器

c++ - double = 安全 vector 的 C++ vector 赋值?

c++ - CFileDialog (MFC) 异常

c++ - 创建 x 个数组