邮政编码验证漏洞,只返回3位数

时间:2016-09-11 16:48:08

标签: c++ debugging

我正在开展一个小型实验室项目,其目的是以下列格式验证邮政编码:

ldl dld (l = letter, d = digit)

到目前为止,我发现它相对简单。但是,在编译时,我发现邮政编码输出只有3个字符长(如果有空格,可能是4)。

如果有人可以帮助指出我哪里出错了,我会非常感激:)。

/* Lab direction:
   Write a program that prompts the user to enter a Canadian postal code in the formal of ldl dld, where d is a digit and l is a letter.
   Check it's validity.
*/

#include <iostream>
#include <cctype>
using namespace std;

int main() {
    // Inform user of the purpose of program
    cout << "This program will check the validity of your Canadian postal code";
    string pc;

    //Prompt user for postal code info
    cout << "Please enter your postal code";
    cin >> pc;

    //Check is character is an int or a letter and in proper order
    bool validCode = true;

    //Check postal code length
    if (pc.length() > 7) 
        validCode = false;

    //Check for space
    if (pc.length() == 7)
        pc.erase(pc.begin()+3);

    for (int i = 0; i < pc.length(); i++) {
        if ((i%2==0)&&(isdigit(i))){
            validCode = false;
        } else if ((i%2!=0)&&(isalpha(i))) {
            validCode = false;
        } else {

        }
    }
    pc.insert(3, 1, ' ');
    if (validCode) {
        cout << pc << " is a valid postal code";
    } else {
        cout << pc << " is not a valid postal code";
    }
    return 0;
}

1 个答案:

答案 0 :(得分:1)

cin >> pc;更改为std::getline(cin, pc);(否则,请输入不带空格的代码)。后者读取整行,而前者在第一个空格处停止。