我正在处理此代码,它与cin>>partname;一起使用,而不是在showpart函数中使用getline(cin, partname);,但仅适用于没有空格的名称。但是使用getline(cin, partname);会产生错误error: no matching function for call to ‘getline(std::istream&, const string&)’

#include<iostream>
#include<cstring>

using namespace std;

class Inventory
{
  private:
    int partno;
    string partname;
    float cost;
    void getpart()
    {
      cout<<"Enter the part number"<<endl;
      cin>>partno;
      cout<<"Enter the part name"<<endl;
      cin>>partname;
      cout<<"Enter the cost"<<endl;
      cin>>cost;
    }

  public:
    Inventory()
    {
      partno = 0;
      partname = " ";
      cost = 0.0;
    }

    Inventory(int pn,string pname,float c)
    {
      partno = pn;
      partname = pname;
      cost = c;
    }

    void setpart()
    {
      getpart();
    }

    void showpart() const
    {
      cout<<"Inventory details"<<endl;
      cout<<"Part Number: "<<partno<<endl;
      cout<<"Part Name: ";
      getline(cin, partname);
      cout<<"\nCost: "<<cost<<endl;
    }
};

int main()
{
  Inventory I1(1,"Resistor", 25.0), I2;
  I2.setpart();
  I1.showpart();
  I2.showpart();
}
我已经浏览过类似的错误,但它们似乎没有帮助。感谢您仔细阅读。

最佳答案

#include <string>而不是<cstring>
也:
因为您更新了void showpart() const,所以const不能是partname(这对于名为show -something的函数来说是奇怪的 Activity )。
我怀疑您想显示partname而不是对其进行更新:

void showpart() const
{
  cout<<"Inventory details"<<endl;
  cout<<"Part Number: "<<partno<<endl;
  cout<<"Part Name: "<<partname<<endl;
  cout<<"Cost: "<<cost<<endl;
}

关于c++ - 使用getline会给出错误:没有匹配函数可以调用 ‘getline(std::istream&, const string&)’,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/62675858/

10-11 22:42
查看更多