循环遍历字符数组c ++

时间:2016-07-30 06:54:23

标签: c++ arrays

#include <iostream>
#include <string>

using namespace std;
bool custNum(char [], int);


int main()
{

    const int size = 8;
    char custmor[size];

    cout << "Enter a customer number in the form ";
    cout << "LLLNNNN\n";
    cout << "(LLL = letters and NNNN = numbers): ";
    cin.getline(custmor, size);
    if(custNum(custmor, size))
        cout<<"That's a valid id number"<<endl;
    else
        cout<<"That's not a valid id number"<<endl;




        return 0;
}
bool custNum(char custNum[], int size)
{
    int count;

    for(count = 0; count<3; count++)
    {

        if(!isalpha(custNum[count]))
            return false;
    }
    for(count = 3; count <size - 1; count++) //3<7 , 4
    {
        if(!isdigit(custNum[count]))
            return false;
    }
    return true;

}

所以我想循环一个包含3个字母和4个数字的字符数组,比如ABC1234,但我没有得到第二个for循环的条件(size-1)。每次测试条件时它如何工作?

2 个答案:

答案 0 :(得分:2)

  1. 切勿将count用作循环变量。循环变量的一个好名称是i

  2. 永远不要在初始化之外声明变量。在这两种情况下,上述内容应为for( int i = 0; ...

  3. i < size - 1可能错了。你可能想要的是i < size

  4. 无论如何,如果你展示如何声明size,如何初始化等等,它会有所帮助。如果你展示了你想要解析的确切文本,它也会有所帮助。如果你准确地解释了你预期会发生什么,以及恰恰发生了什么,这也会有所帮助。当你这样做时,我可能会修改我的答案。

答案 1 :(得分:0)

你只读取大小变量指定的字符数量, 从那时起,为什么custNum函数不会返回true而不是size变量? ,因为它没有检查任何大小变量指定的内容。

以下是您需要的代码

      #include <iostream>
#include <string>

using namespace std;
bool custNum(string,unsigned int);


int main()
{

    const unsigned int size = 8;
    //char custmor[size];

    string mystring;

    cout << "Enter a customer number in the form ";
    cout << "LLLNNNN\n";
    cout << "(LLL = letters and NNNN = numbers): ";
    cin >> mystring;

    cout << mystring <<endl << " " <<   mystring.length() << endl;
    // cin.getline(custmor, size);


     if(custNum(mystring , size))
        cout<<"That's a valid id number"<<endl;
    else
        cout<<"That's not a valid id number"<<endl;




        return 0;
}
bool custNum(string s, unsigned int size)
{
    unsigned int count;

    if (s.length() != (size + 1))
        return false;

    for(count = 0; count<3; count++)
    {

        if(!isalpha(s[count]))
            return false;
    }
    for(count = 3; count <size - 1; count++) //3<7 , 4
    {
        cout <<  s[count] <<endl;
        if(!isdigit(s[count]))
            return false;
    }
    return true;

}