C++试图通过getline函数为函数调用提供用户输入值



我正试图使用class创建一个程序,通过用户输入,可以执行勾股定理的运算,但我得到了这个错误:

错误(活动(E0304没有重载函数"getline"的实例与参数列表匹配

这是我的代码:

#include <iostream>
#include <cmath>
#include <string>
using namespace std;
class PythagoreanTheorum
{
public:
double a;
double b;
double c;
void seta(double A)
{
a = A;
}
void setb(double B)
{
b = B;
}
void setc(double C)
{
c = C;
}
double calcAreea()
{
return a * pow(a, 2) + b * pow(b, 2) == c * pow(c, 2);
}    
};

int main()
{
//Define one right triangles
PythagoreanTheorum righttriangle1;
double a;
double b;
double c;
cout << "Enter the value for a: " << endl;
righttriangle1.a = getline(cin, a);
cout << "Enter the value for b: " << endl;
righttriangle1.b = getline(cin, b);

cout << "Enter the value for c: " << endl;
righttriangle1.c = getline(cin, c);


}

std::getline读取字符串,而不是双精度。因此,您必须使用std::string进行读取,然后将其转换为double(使用stod(。

您也可以使用>>运算符进行输入:

cout << "Enter the value for a: " << endl;
std::cin >> righttriangle1.a;
cout << "Enter the value for b: " << endl;
std::cin >> righttriangle1.b;
cout << "Enter the value for c: " << endl;
std::cin >> righttriangle1.c;

这就是我编写代码的方式,假设代码中的calcAreea((旨在显示应用的勾股定理。

我的代码:

#include <iostream>
#include <cmath>
using namespace std;
class PythagoreanTheorum
{
public:
void seta(double A)
{
a = A;
}
void setb(double B)
{
b = B;
}
void setc(double C)
{
c = C;
}
double calcTheorem()
{
cout<<"Applying Pythagoreas Theorem:"<<pow(a,2)<<"+"<<pow(b,2)<<"="<<pow(c,2);
}    
private:
double a;
double b;
double c;
};

int main()
{
//Define one right triangles
//Test -> a = 3, b = 4, c = 5
PythagoreanTheorum righttriangle1;
double a;
double b;
double c;
cout << "Enter the value for a: " << endl;
cin>>a;
righttriangle1.seta(a);
cout << "Enter the value for b: " << endl;
cin>>b;
righttriangle1.setb(b);
cout << "Enter the value for c: " << endl;
cin>>c;
righttriangle1.setc(c);
righttriangle1.calcTheorem();
}

我删除了字符串头文件,因为它没有被使用,我还使用了cin而不是getline,因为在这种情况下更好,而且我不想使用命名空间std;但由于它在你的代码中,我保留了它&也将calcAreea重命名为calcTheorem,因为它不计算面积

编辑:我忘了提到我在类中以私有而非公共声明了变量

最新更新