//C++ program two find number of days between two given dates
#include "stdafx.h"
#include<iostream>
#include<string>
using namespace std;
// A date has day 'd', month 'm' and year 'y'
// 'h' hour , 'min' minute ; 'sec' second
struct Date
{
int d, m, y, h, min, sec;
};
问题主要在于:
int main(int argc, char** argv)
{
string line;
getline(cin, line);
int test = stoi(line);
unsigned int * tab = new unsigned int[test];
for (int i = 0; i <test; i++)
tab[i] = 0;
for (int i = 0; i<test; i++)
{
getline(cin, line);
int n1 = stoi(line);
int n2 = stoi(line);
tab[i] = getDifference(n1, n2); // HERE IS PROBLEM
}
for (int i = 0; i<test; i++)
{
cout << tab[i] << endl;
}
弹出错误: 没有适当的构造函数将“int”重定向到“Date”
如何解决? 我的任务是通过CMD下载数据,第一行是测试次数,接下来是5组日期来计算它们之间的天数差异。你知道如何告诉程序前两行是一组吗?
答案 0 :(得分:0)
您需要将每个数字分别读入Date
- 对象的成员,然后比较Date
- 对象,而不仅仅是单个整数。
策略是阅读完整的行(例如“20 10 2017”),然后使用stringstream
阅读单独的数字:
#include <sstream>
struct Date
{
int d, m, y, h, min, sec;
};
ostream& operator << (ostream& o, Date & d) {
o << d.d << "/" << d.m << "/" << d.y;
return o;
};
int main() {
std::string line;
if (std::getline(std::cin,line)) {
int nrOfSets = 0;
stringstream reader(line);
reader >> nrOfSets;
int i=0;
Date previousDate;
while (i < nrOfSets && getline(cin,line)) {
Date d;
reader = stringstream(line);
if (! (reader >> d.d >> d.m >> d.y)) {
cout << "invalid input." << endl;
continue;
}
i++;
if (i > 1) { // already two dates entered?
cout << "calculating difference between " << d << " and " << previousDate << ":" << endl;
// your code: int difference = calcDifference(d, previousDate);
}
previousDate = d;
}
}
}
输入/输出:
2
20 10 2017
22 10 2017
calculating difference between 22/10/2017 and 20/10/2017: