if字符串验证循环出现问题

Issues with if string validation loop

本文关键字:问题 循环 字符串 验证 if      更新时间:2023-10-16

我正在进行一个验证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";
   }
}

我是新手,但我认为我走在了正确的道路上。couts将测试循环是否工作。它直接进入另一个状态。这是一个样本输入

||:|:::|:

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

您的字符串的长度为32,因此if条件为false,因为check.length()==31。此外,循环中的if条件需要"&&"而不是"||",因为您希望它既不是"|"也不是":",成为不可接受的条形码。

更改以粗体标记。

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