是否有方法将整数转换为字符串?


#include <iostream>
using namespace std;
class Vehicles
{
public:
int wh;
void wheels () {
cout << "Enter number of wheels: ";
cin >> wh;
if (wh == 2) {
cout << "You chose a Motorcycle!n";
} else if (wh == 3) {
cout << "You chose a Tricycle!n";
} else if (wh == 4) {
cout << "You chose a Car!n";
}
} 
} ; //type of vehicle
int main () {
Vehicles number;
number.wheels();
int wheels = number.wh;
cout << "Your vehicle is a " << number.wh; //I would like to say it as a car or the other two vehicle, but the code was an integer
}

是否有一种方法可以将整数转换为字符串?我想说它是一辆车还是上面代码中提到的另外两种交通工具,但我不知道应该用哪种代码。

您可以通过整数选择合适的字符串表示为车辆类型。

#include <iostream>
#include <vector>
using namespace std;
vector<string> types {"Weird vehicle", "monocyle", "bike", "tricycle", "car"};
class Vehicles
{
public:
int wh;
void wheels ()
{
cout << "Enter number of wheels: ";
cin >> wh;
} 
} ; //type of vehicle
int main () {
Vehicles number;
number.wheels();
int wheels = number.wh;
cout << "nYour vehicle is a " << types[number.wh]; 
}

您可以移动查找向量,使其成为类的静态部分,然后添加一个静态表示方法,用于将wheel number属性作为字符串输出。

当你说将整型转换为字符串时,我们会考虑将foo = 13转化为foo = "13"

但你需要的是别的东西。

在Vehicle类中定义你自己的方法

std::string Vehicles::getVehicleType ()
{
if (wh == 2) {
return "Motorcycle";
} else if (wh == 3) {
return "Tricycle";
} else if (wh == 4) {
return "You chose a Car!n";
}
}

and in main

int main ()
{
...
cout << "Your vehicle is a " << number.getVehicleType();
}

最新更新