簡體   English   中英

使用 getline 給出錯誤:沒有匹配的 function 調用 'getline(std::istream&, const string&)'

[英]using getline gives error: no matching function for call to ‘getline(std::istream&, const string&)’

我正在處理這段代碼,它適用於cin>>partname; 而不是使用getline(cin, partname); 在展示部分 function 但僅適用於沒有空格的名稱。 但是使用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 的 function 來說,這是一個奇怪的活動)。

我懷疑您想顯示partname ,而不是更新它:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM