如何将数组元素传递给另一个?

时间:2016-11-25 13:56:01

标签: c++ c arrays pointers

我正在尝试为汽车换一块新车并更换旧车。我需要三封信作为首都。问题是我无法将newPlate数组的“capital”元素传递给new_Plate数组。该程序编译,但答案是soometimes%^&#%@ $和其他一些时间没有。我知道我的指针有问题。

void Car::set(char *newBrand, char *newPlate) 
{
    char new_Brand[80];
    char new_Plate[8];

    if(strlen(newPlate)==8)
    {
        for(int i=0;i<3;i++)
        {   
            if(65<=(int)newPlate[i]<=90)
            {
                new_Plate[i]=newPlate[i]; // probably the problem
            }

            if(97<=(int)newPlate[i]<=122)
            {
                new_Plate[i]=(newPlate[i]+32); // probably the problem
            }

            cout<<new_Plate;
        }
    }
}

2 个答案:

答案 0 :(得分:2)

您的namespace PinningTest { class AdminReceiverTest : DeviceAdminReceiver { } } 字符串不包含零终结符。 此外,new_Plate在C ++中无效。你应该写点像

65<=(int)newPlate[i]<=90)

答案 1 :(得分:2)

表达式65<=(int)newPlate[i]<=90除了不可读之外,使用更多空白区域使其更具可读性)的问题在于它意味着((65 <= (int) newPlate[i])) <= 90不是它的意思在数学上似乎意味着。

此表达式始终为真,因为65 <= (int) newPlate[i]将评估为10,并且它当然始终为< 90

此外,为了使代码更具可读性,请使用'A'代替65以及其他任何字符的等效代码。大多数程序员都知道ascii中'A'是65,但是你让他们停下来一两秒钟才意识到你的意思是'A'

此外,您必须使用'\0'终止c-strings,因此最后需要一个额外的字符,cout << new_Plate将调用未定义的行为。

要打印c字符串,库将从输入缓冲区输出字符,直到找到'\0',因为它不存在于缓冲区中,没有可预测的打印方式。

检查一下,你明白这些变化吗?

#include <iostream>
#include <cstring>

using namespace std;

class Car {
public:
    Car();
    void set(const char *const newBrand, const char *const newPlate);
};

Car::Car() 
{
}


void
Car::set(const char *const newBrand, const char *const newPlate) 
{
    char new_Brand[80];
    char new_Plate[9];
    size_t length;
    size_t i;

    (void) new_Brand;
    length = strlen(newPlate);
    for (i = 0 ; ((i < length) && (i < sizeof(new_Plate) - 1)) ; ++i) {   
        if (('A' <= newPlate[i]) && (newPlate[i] <= 'Z')) {
            new_Plate[i] = newPlate[i];
        } else if (('a' <= newPlate[i]) && (newPlate[i] <= 'z')) {
            new_Plate[i] = (newPlate[i] - 32);
        }
    }
    new_Plate[i] = '\0';

    cout << '*' << new_Plate << '*' << endl;
}

int
main(void)
{
    Car car;    
    car.set("audi", "example text");
    return 0;
}
相关问题