这个程序要求您输入三个朋友和他们的披萨切片的直径。
然后,它计算披萨的面积,并看到谁的切片最大。
我需要一些帮助,尝试将getline放入我的字符串函数中,以摆脱代码中的重复。
#include <iostream>
#include <cmath>
#include <iomanip>
#include <string>
using namespace std;
string presentStringPrompt(string);
double presentDoublePrompt(string);
double computeAreaOfCircle(double);
const double pi = 3.14159;
int main() {
string first;
string second;
string third;
double diameter;
double radius;
double area1;
double area2;
double area3;
cout << "Enter the name of the first friend: ";
getline(cin, first);
cout << "Enter " << first << " pizza diameter : ";
cin >> diameter;
cin.ignore();
radius = diameter / 2;
area1 = pi * radius * radius;
cout << "Enter the name of the second friend: ";
getline(cin, second);
cout << "Enter " << second << " pizza diameter : ";
cin >> diameter;
cin.ignore();
radius = diameter / 2;
area2 = pi * radius * radius;
cout << "Enter the name of the third friend: ";
getline(cin, third);
cout << "Enter " << third << " pizza diameter : ";
cin >> diameter;
radius = diameter / 2;
area3 = pi * radius * radius;
cout << showpoint << fixed << setprecision(1);
cout << " The area of " << first << "'s pizza is " << area1 << " inches squared " << endl;
cout << " The area of " << second << "'s pizza is " << area2 << " inches squared " << endl;
cout << " The area of " << third << "'s pizza is " << area3 << " inches squared " << endl;
if (area1 >= area2 && area1 >= area3) {
cout << first << " has the largest slice of pizza." << endl;
}
else if (area2 >= area1 && area2 >= area3) {
cout << second << " has the largest slice of pizza." << endl;
}
else {
cout << third << " has the largest slice of pizza" << endl;
}
cin.ignore();
cin.get();
return 0;
}
string presentStringPrompt(string) {
string value;
getline(cin,value);
return value;
cin.ignore();
}
double presentDoublePrompt(string) {
}
double computeAreaOfCircle(double) {
}
在您以前的格式文本提取中的输入流中留下了一个'n'
字符。
这就是为什么第一个后续getline()
语句之后失败的原因。
您可以在此处获取有关如何解决该问题的更多信息:
为什么std :: getline((在格式提取后跳过输入?
内部内部您必须调用此功能
int main()
{
cout << "Enter the name of the first friend: ";
first = presentStringPrompt(first);//or you can use pass by reference that way you don't have to do first =
cout << "Enter " << first << " pizza diameter : ";
cin >> diameter;
cin.ignore();
}
string presentStringPrompt(string value)
{
getline(cin,value);
return value;
}
模板怎么样?
template <typename T> question(char * question)
{
T reply;
cout << question;
cin >> reply;
cin.ignore();
return reply;
}
用作
double diameter = question("Enter " + first + " pizza diameter :");
几个注:
如果您将"用于字符串,则不需要终止char,它是由编译器添加的。
返回后不要添加行,不会执行它。