有没有办法将整数转换为字符串?

时间:2021-01-22 07:47:00

标签: c++

#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
}

有没有办法转换整数并使其成为字符串?我想说它是一辆车还是上面代码中提到的另外两种车辆,但我不知道我应该使用哪个代码。

2 个答案:

答案 0 :(得分:2)

当你说convert int to string时我们会想到 将 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";
    }
}

并在主

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

答案 1 :(得分:2)

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

#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]; 
}

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