【问题标题】:why my code does not work when I put Variables inside vector with + operand为什么当我将变量放在带有 + 操作数的向量中时我的代码不起作用
【发布时间】:2021-12-14 22:45:06
【问题描述】:

//此代码有效。

//主驱动

#include <iostream>
#include <string>
#include <vector>
using namespace std;

int main()
{
    string name, age;

    name = "Muzaib";
    age = "16";

    std::vector<std::string> B = {name + "\n" + age + "lll" + '\n'};
    B.push_back(name + '\n' + age);
    cout << B[0];
     cout << B[1];
    return 0;
}

//此代码不起作用。

#include <iostream>
#include <vector>
#include <string>
#include <cstdlib>
using namespace std;

//医生类

class Doctor : public Hospital
{
    protected:
        std::vector<std::string> doctors;               //contains list of doctors.
        string Docname;
        int Docage;
        string Docgender;
        string specialty;

    public:
        Doctor();                       //Constructor
        void listDoctors();
        void addDoctor();
        void removeDoctor();
    
};

// 允许用户将医生添加到列表中。

void Doctor::addDoctor()
{
    cin.ignore();
    cout << "Enter Doctors name: ";
    getline(cin, Docname);
    cout << "\nEnter Soctors age: ";
    cin >> Docage;
    cin.ignore();
    cout << "\nEnter Doctors gender";
    getline(cin, Docgender);
    cout << "\nEnter Doctors specialty: ";
    getline(cin, specialty);

//这行代码给了我以下错误:[Error] no match for 'operator+' (operand types are 'std::basic_string' and 'int') 我在其他程序上没有收到任何错误。

    doctors.push_back(Docname + '\n' + "Age: " + Docage + '\n' + "Gender: " + Docgender + '\n' 
    + "Specialty: " + specialty);
}

【问题讨论】:

  • stackoverflow.com/a/69729646/13421519 这是我学习如何做到这一点的链接。
  • 基本上,我只是想将所有这些信息放在向量的同一个地址中。
  • 这与向量无关。 std::string s = "hello"; int x = 42; s + x; 已经重现该错误。正如错误消息明确指出的那样,您不能连接字符串和 int。先把数字转成字符串,如... + std::to_string(Docage) + ...

标签: string class c++11 vector


【解决方案1】:

我认为你应该试试下面的代码:

doctors.push_back(Docname + '\n' + "Age: " + std::to_string(Docage) + '\n' + "Gender: " + Docgender + '\n' + "Specialty: " + specialty);

Docageint 类型,所以首先必须转换为string 类型 为了能够将值与其他字符串连接起来。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多