我要编写一个程序,它需要输入一个药品的名称,然后从用户其数量。然后,它必须计算与给定值的数量。但是,我正在用“*”(乘法运算符)的错误。下面给出的错误。
Error: no operator "*" matches these operands
operator types are: std::string * int
请帮我解决这个问题。我还附上了我的代码,你也可以看到error清楚。
#include <iostream>
#include <conio.h>
#include <string>
using namespace std;
void main()
{
string med,quantity,panadol=0,piozer=0,burofen=0;
cout << "Pharmacy Management System" ;
cout << "\n Enter your Medicine Name : ";
getline(cin,med);
cout << "\n Enter your Medicine Quantity : ";
getline(cin,quantity);
int a,b;
if (med==panadol && med==burofen)
{
a= (quantity*2);
cout << a;
}
if (med==piozer)
{
b= (quantity*14);
cout << b;
}
getch();
}
有没有在你的代码中的一些基本的误解。你必须决定什么是可变的,什么不是,当你使用一个变量,你必须决定它是什么类型。
似乎有在你的代码的三个基本错误
string med,quantity,panadol=0,piozer=0,burofen=0;
panadol
,poizer
和burofen
是要看到,如果用户输入药品名称。因此,他们不应该是变量,他们应该是字符串文字。像这样
if (med == "piozer")
{
b= (quantity*14);
cout << b;
}
请参阅“piozer”是一个字符串文字,上面的代码询问是否med
等于“piozer”。所以删除piozer
变量,并用字符串文字,同与所有其他药品名称替换。这是解决你的问题invalid null operator
。
第二个错误是,quantity
应该是一个int
。这应该是显而易见的,要乘以数量,你怎么能繁殖的字符串?
第三个错误是在这里
if (med == "panadol" && med == "burofen")
这不可能是真的,med
等于“必理通”和med
等于“burofen”。这是逻辑上不可能的一个变量是在同一时间等于两个不同的值。显然你真正的意思是这样的
if (med == "panadol" || med == "burofen")
如果med
等于“必理通”,或者如果一方是真实的,如果不同时为真med
等于“burofen”,即。
Quantity
是string
,2
是int
。你不能*
一起string
和int
。
也许你想stoi
上quantity
?
您的变量quantity
是一个字符串。你得到,因为你试图通过一个数乘以串的错误。除了使用功能getLine()
的,应该用来检索字符串,尝试做如下图所示:
cin >> quantity;