經典的類運算符重載和類定義,我相信你可能會有很多懷疑。爲什麼這麼複雜,但涉及到很多細節和簡單的使用。
// Test1.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
// Lap_time class represents minutes and seconds
struct lap_time {
int minutes;
int seconds;
// Default constructors
lap_time() : minutes(0),seconds(0) { }
lap_time(const string& str) {
stringstream ss(str);
string value;
if (std::getline(ss, value, ':'))
minutes = stoi(value);
if (std::getline(ss, value, ':'))
seconds = stoi(value);
}
lap_time(int m, int s) : minutes(m), seconds(s) { }
// input operator overload
friend istream& operator >> (istream& is, lap_time&);
// output operator overload
friend ostream& operator << (ostream& os, lap_time&);
// Time multiply operation
lap_time operator*(const int& x) {
int time = (this->minutes) * 60 + this->seconds;
time = time * 2;
return lap_time(time/60, time % 60);
}
};
// input operator overload declaration
istream& operator>>(istream& is, lap_time& lt)
{
string laptime;
is >> laptime;
stringstream ss(laptime);
string value;
if (std::getline(ss, value, ':'))
lt.minutes = stoi(value);
if (std::getline(ss, value, ':'))
lt.seconds = stoi(value);
return is;
}
// ouput operator overload declaration
ostream& operator<<(ostream& os, lap_time& lt)
{
stringstream ss;
ss << lt.minutes << ":" << lt.seconds;
os << ss.str();
return os;
}
// getline function overload to read lap_time
void getline(std::istream& is, lap_time& lt)
{
string laptime;
is >> laptime;
stringstream ss(laptime);
string value;
if (std::getline(ss, value, ':'))
lt.minutes = stoi(value);
if (std::getline(ss, value, ':'))
lt.seconds = stoi(value);
}
int main()
{
string car_number1;
string car_number2;
string car_number3;
string car_color1;
string car_color2;
string car_color3;
lap_time race_time1;
lap_time race_time2;
lap_time race_time3;
cout << "We are doing a 2 lap race." << ' ' << endl;
//Data for car 1
cout << "Enter a number for the first race car: " << endl;
cin >> car_number1;
cin.ignore();
cout << "Enter a color for car number " << car_number1 << endl;
getline(cin, car_color1);
cout << "Enter a lap time in MM:SS: for the " << car_color1 << ' ' << car_number1 << ' ' << "car" << endl;
getline(cin, race_time1);
cout << "Single Lap race time is :" << race_time1 << endl;
// I do not think you should multiply by two unless assuming both laps equal timing.
cout << "Two lap race time is : " << (race_time1 * 2) << endl;
}
爲什麼您使用的字符串?只需'int a; cin >> a'本來可以做到這一點 –
爲自己省事,從一開始就用'int'。 –
即使你首先閱讀字符串,也有'std :: stoi' – Dutow