【问题标题】:if statement isnt comparing numerical values in my string c++if语句没有比较我的字符串c ++中的数值
【发布时间】:2018-08-19 07:44:01
【问题描述】:

分配是让用户输入具有特定要求的密码,例如长度、大写/小写字母和数字。当我尝试运行在字符串中添加数字数量的 for 循环时,它似乎跳过了 if 语句。

 #include <iostream>
 #include <cstring>
 #include <stdlib.h>
 using namespace std;

 int main()
 {
  const int LENGTH = 13;
  char str[LENGTH];
  int size = 0, k = 0, j = 0, r = 0;

 cout << "Enter a password." << endl;
 cout << "Must meet these requirements:" <<  endl;
 cout << "At least 10 and at most 12 characters." << endl;
 cout << "Any characters entered after 12 will be ignored." << endl;
 cout << "At least 2 lower case, and 2 upper case letters." << endl;
 cout << "At least 3, but no more than 5 numerical digits." << endl;
 cout << "No white spaces." << endl;

 cin.getline(str, LENGTH);

//Validating numerical values.
for (int z=0; z < 12; z++)
{
 if (str[z] >=0 && str[z] <=10)
{
 r++;
 }
}

 if (r<3 || r>5)
 {
cout << "Must have at least 3 but no more than 5 numerical digits."<<endl;
 exit (EXIT_FAILURE);
}

【问题讨论】:

  • str[z] &gt;=0 &amp;&amp; str[z] &lt;=10 => str[z] &gt;='0' &amp;&amp; str[z] &lt;='10'。字符和数字不是一回事。您需要检查 ASCII 值
  • @Mitchel0022 -- '10' 是一个有效的字符常量,但在这里没用。

标签: c++ string validation for-loop if-statement


【解决方案1】:

在您的代码中,您正在检查 0 到 10 之间的 ASCII 值,但您想检查“0”和“9”之间的字符。 您可以在 ASCII 表中检查这些字符的值并使用这些值:

if(str[z] >= 60 && str[z] <= 71)

或使用字符:

if(str[z] >='0' && str[z] <='9')

【讨论】:

  • 不要使用 ASCII 值。使用'0''9'
猜你喜欢
  • 2018-10-15
  • 1970-01-01
  • 1970-01-01
  • 2016-07-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多