我有以下代码来打印出Car对象。所有字段均可公开访问。
void print_cars_array(Car cars[]) {
/**
* Prints all cars in the given car array.
*/
for(int i = 0; i < NUM_CARS; i++) {
std::cout << "Car #" << i + 1 << std::endl;
std::cout << cars[i].year << ' ' << cars[i].color << ' ' << cars[i].make << ' ' << cars[i].model << std::endl;
}
}
但是,这给了我以下输出:
Car #1
Subaru Outback
Car #2
Toyota Corolla
...
起初我以为前两个字段搞砸了,但是修改了这个循环:
void print_cars_array(Car cars[]) {
/**
* Prints all cars in the given car array.
*/
for(int i = 0; i < NUM_CARS; i++) {
std::cout << "Car #" << i + 1 << std::endl;
std::cout << cars[i].year << std::endl;
std::cout << cars[i].color << std::endl;
std::cout << cars[i].year << ' ' << cars[i].color << ' ' << cars[i].make << ' ' << cars[i].model << std::endl;
}
}
产生以下内容:
Car #1
2016
green
Subaru Outback
Car #2
2006
white
Toyota Corolla
我是否想知道为什么不打印这些内容?除year
外的所有字段均为字符串,而year
为整数。
答案 0 :(得分:1)
尝试to_string()
,因为问题可能是整数和字符串类型串联