123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105 | #include <iostream>#include <strings.h>#include <sstream>#include <locale.h> using std::cout;using std::cin;using std::string; struct TIME { int hh; int mm; double seconds;}; TIME convertTime(double secs);TIME addTime(TIME a, TIME b);void printTimeln(TIME a);TIME stringToTIME (string texto); int main(){ setlocale(LC_ALL,""); string tempo1="", tempo2=""; cout << "Este programa soma dois tempos no formato hh:mm:ss.ss\n"; TIME tempo1 = stringToTIME ("primeiro"); TIME tempo2 = stringToTIME ("segundo"); TIME resultado = addTime (tempo1,tempo2); //printTimeln(tempo1); //printTimeln(tempo2); cout <<"Resultado da soma: "; printTimeln (resultado); return 0;} TIME addTime(TIME a, TIME b){ double tempo1=a.hh*3600+a.mm*60+a.seconds; double tempo2=b.hh*3600+b.mm*60+b.seconds; return convertTime(tempo1+tempo2);} TIME convertTime(double secs){ TIME tempo; tempo.hh= secs / 3600; tempo.mm= (secs - tempo.hh*3600)/60; tempo.seconds= secs - tempo.hh*3600 - tempo.mm*60; return tempo;}; void printTimeln(TIME a){ cout << a.hh << ":" << a.mm << ":" << a.seconds <<"\n";} TIME stringToTIME (string texto){ string temp=""; TIME tempo; while (true){ bool erro=false; cout << "\nDigite o "<< texto << " tempo: "; cin >> temp; int pos1=temp.find(':'); int pos2=temp.find(':',pos1+1); int pos3=temp.find('.'); //cout <<"pos1: " <<pos1; //cout <<"\npos2: " <<pos2; //cout <<"\npos3: " <<pos3; //Na validação eu não exigo que cada valor de hora ,minutos e segfundos tenha dois algarismo if (pos1<1 || pos2<2) erro=true; // a presença do ponto é opcional if (pos2-pos1<2) erro=true; if (pos3 >-1 && pos3-pos2<2) erro=true; //mas se estiver presente tem que ser o terceiro símbolo for (int i=0; i< temp.length();i++){ if (!isdigit( temp.at(i))){ if(temp.at(i)!=':' && temp.at(i)!='.') erro=true; }; }; //Eu pretendia separar validação e conversão em funções distintas, mas como ambas //dependem das variáveis pos* eu desisti if (!erro){ // cout << "\nhoras: " << temp.substr(0,pos1); // cout << "\nminutos: " << temp.substr(pos1+1,pos2-pos1-1); // cout << "\nsegundos: " << temp.substr(pos2+1,temp.length()-pos2-1) << '\n'; tempo.hh = stoi(temp.substr(0,pos1)); tempo.mm = stoi(temp.substr(pos1+1,pos2-pos1-1)); temp.at(pos3)=','; //gambiarra: a função stof() requer vírgula no meu SO. Se deixar o ponto ela descarta a parte fracionária tempo.seconds = stof(temp.substr(pos2+1,temp.length()-pos2-1)); break; } else cout << "\nFormato inválido. Tente de novo." << '\n'; }; return tempo; }; |