Hi friends,

I have an assignment to put three little programs into one, making each one a function of the main program, which is a kind of menu. The three work perfectly as separate entities, but when I put them together, the thing won't compile. Can anyone tell me what's wrong here?

The programs (functions) are:

1. A dice simulator
2. A program for calculating the number of days between two dates, taking leap years into consideration
3. A program for calculating the cost of a telephone call during different times of the day.

#include "MainProgram.h"
//--------------------------------------------------------------------------------------------------
// Namn:    diceSim
// Uppgift: Programmet från uppgift 1
// Indata : -
// Utdata : -
//--------------------------------------------------------------------------------------------------

void diceSim()
{
  dos_console(850);
	
  int frekvens[7] = {0, 0, 0, 0, 0, 0, 0};
  int resultat;
  int antalKast;                      

  cout << "VÄLKOMMEN TILL TÄRNINGSSIMULATORN!" << endl;				// Huvudrubrik
  cout << "==================================" << endl << endl; 
  cout << "Detta program simulerar det antal tärningskast som anges av användaren." << endl;
  cout << "Var god mata in antalet kast (1-1000): ";
  cin >> antalKast;													// Inmatning för angivna kast

  while (antalKast <= 0 || antalKast > 1000)						// Kontrollerar att värdet = 1-1000
  {
cout << "Felaktig inmatning! Försök igen: ";
    cin >> antalKast;
  }
  cout << endl;

  srand(time(0));													// Använder systemklockan som slumpgenerator

  // Slumpar antalet kast som angivits och uppdaterar tabellen
  for (int i = 1; i <= antalKast; i++)
  {
    resultat = rand()%6 + 1;										// Får ett slumpmässigt tal 1-6
    frekvens[resultat]++;
  }

  // Skriver ut tabellen "frekvens"
  for (resultat = 1; resultat <= 6; resultat++)
  cout << resultat << ": " << setw(7) << frekvens[resultat] << endl;
  cout << endl;
  cout << "===========================================" << endl;
  cout << endl;
  
  // Skriver ut tabellen "relativ frekvens"
  cout << fixed << setprecision(2);
  cout << "Relativ frekvens för ettor: "
       << setw(5) << static_cast<float>(frekvens[1])/static_cast<float>(antalKast) << endl;
    
  cout << fixed << setprecision(2);
  cout << "Relativ frekvens för tvåor: "
       << setw(5) << static_cast<float>(frekvens[2])/static_cast<float>(antalKast) << endl;
	  
  cout << fixed << setprecision(2);
  cout << "Relativ frekvens för treor: "
       << setw(5) << static_cast<float>(frekvens[3])/static_cast<float>(antalKast) << endl;
	
  cout << fixed << setprecision(2);
  cout << "Relativ frekvens för fyror: "
       << setw(5) << static_cast<float>(frekvens[4])/static_cast<float>(antalKast) << endl;

  cout << fixed << setprecision(2);
  cout << "Relativ frekvens för femmor: "
       << setw(4) << static_cast<float>(frekvens[5])/static_cast<float>(antalKast) << endl;

  cout << fixed << setprecision(2);
  cout << "Relativ frekvens för sexor: "
       << setw(5) << static_cast<float>(frekvens[6])/static_cast<float>(antalKast) << endl;

  cout << endl;

  system("pause");
}

//--------------------------------------------------------------------------------------------------
// Namn:    countDays
// Uppgift: Programmet från uppgift 2
// Indata : -
// Utdata : -
//--------------------------------------------------------------------------------------------------
void countDays()
{  
  dos_console(850);
  bool restart;                                                 // Avgör om programmet skall upprepas
  do
  { 
    string startDate, endDate;
    system("cls");                                              // Rensar skärmen
    cout << " Detta program beräknar antalet dagar mellan två datum (tidigast 1/1 1900)" << endl;
    cout << " =========================================================================" << endl << endl;
    cout << " Ange startdatum (ÅÅÅÅMMDD): ";
    cin >> startDate;                                           // Inmatning till variabeln startDate
    cout << " Ange slutdatum (ÅÅÅÅMMDD) : ";
    cin >> endDate;                                             // Inmatning till variabeln endDate
    cout << endl;

    // Anropar funktionen days och skriver ut antalet dagar
    cout << " Antal dygn emellan = " << days (startDate, endDate) << endl << endl;

	cout << " Vill du göra en ny beräkning? (j/n)" << endl;
    char ch;
    do
    {
      ch = _getch();
      ch = toupper(ch);                                         // Fungerar med versaler
      if (ch == 'J')                                 
	    restart = true;                                                                                                                   
      if (ch == 'N')                   
        restart = false;
	}while (!(ch == 'J' || ch == 'N'));

  }while (restart);                                             // Upprepar programmet om sant
}
//--------------------------------------------------------------------------------------------------
// Funktionsdefinitioner
//--------------------------------------------------------------------------------------------------
// Namn: leapYear
// Uppgift: Kontrollerar skottår
// Indata: Årtal (heltal)
// Utdata: true/false
//--------------------------------------------------------------------------------------------------
bool leapYear(int year)
{  // Beräkning av skottår
   return year%4 == 0 && (year%100 != 0 || year%400 == 0);
}
//--------------------------------------------------------------------------------------------------
// Namn: daysInMonth
// Uppgift: Beräkna antalet dagar i en månad
// Indata: Årtal (heltal)
//         Månadsnummer (heltal)
// Utdata: Antal dagar i respektive månad, med hänsyn till skottår (heltal)
//--------------------------------------------------------------------------------------------------
int daysInMonth(int month, int year)
{
  // Innehållet 0-12 i vektorn motsvararar antalet dagar i varje månad
  int daysInMonth[13] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

  if (leapYear(year))         // Anropar funktionen leapYear
     daysInMonth[2] = 29;     // Februari får 29 dagar om skottår

  return daysInMonth[month];
}
//--------------------------------------------------------------------------------------------------
// Namn: daysFrom1900
// Uppgift: Beräkna antalet dygn från 31/12 1899 fram till ett givet datum
// Indata: År (heltal), månad (heltal), dag (heltal)
// Utdata: Antal dygn från 31/12 1899 till angivet datum (heltal)
//--------------------------------------------------------------------------------------------------
int daysFrom1900(int year, int month, int day)
{ 
  int yearsFrom1900 = 0;
  int daysFrom1900  = 0;
  int monthsDays    = 0;

  // Ökar på dagarna för året fram till angivet år
  for (yearsFrom1900 = 1900; yearsFrom1900 < year; yearsFrom1900++)
  {
    if (leapYear(yearsFrom1900))                        // Anropar funktionen leapYear
	  daysFrom1900 += 366;
	else
	  daysFrom1900 += 365;
  }

  // Ökar på dagarna för månaderna fram till angiven månad
  for (monthsDays = 0; monthsDays < month; monthsDays++)
  {
    daysFrom1900 += daysInMonth(monthsDays, year);      // Anropar funktionen "daysInMonth"
  }

  // Ökar på dagen för månaden och returnerar totalsumma
  return daysFrom1900 + day;
}
//--------------------------------------------------------------------------------------------------
// Namn: days
// Uppgift: Beräkna antalet dygn mellan två datum
// Indata: Startdatum som en sträng på formen ÅÅÅÅMMDD
//         Slutdatum som en sträng på formen ÅÅÅÅMMDD
// Utdata: Antalet dygn från startdatum till slutdatum (heltal)
//--------------------------------------------------------------------------------------------------
int days(string d1, string d2)
{ 
  // Plockar ut årtal, månad och dag med substring ur sträng d1 och d2
  string d1YearStr  = d1.substr(0,4);
  string d1MonthStr = d1.substr(4,2);
  string d1DayStr   = d1.substr(6,2);
  string d2YearStr  = d2.substr(0,4);
  string d2MonthStr = d2.substr(4,2);
  string d2DayStr   = d2.substr(6,2);

  // Omvandlar strängar till heltal
  int d1Year  = atoi(d1YearStr.c_str());
  int d1Month = atoi(d1MonthStr.c_str());
  int d1Day   = atoi(d1DayStr.c_str());
  int d2Year  = atoi(d2YearStr.c_str());
  int d2Month = atoi(d2MonthStr.c_str());
  int d2Day   = atoi(d2DayStr.c_str());

  // Anropar funktionen "daysFrom1900", returnerar sedan antalet dagar mellan datumen
  return daysFrom1900(d2Year, d2Month, d2Day) - daysFrom1900(d1Year, d1Month, d1Day);
}

//--------------------------------------------------------------------------------------------------
// Namn:    teleRate
// Uppgift: Programmet från uppgift 3
// Indata : -
// Utdata : -
//--------------------------------------------------------------------------------------------------
void teleRate()
{  
    dos_console();
    
    bool restart;                                                 // Avgör om programmet skall upprepas
    
    cout << endl;
	cout << " RingPling 2004 AB" << endl;                         // Huvudrubrik
    cout << " =================" << endl << endl;
	cout << " Beräknar samtalskostnad" << endl <<endl;

	do
	{
	  string start, stop;                                        // Sträng-variabler
	  cout << endl;
	  cout << " Ange starttid (hh:mm): ";
      cin >> start;                                              // Inmatning till start
	  cout << " Ange sluttid (hh:mm) : ";
      cin >> stop;                                               // Inmatning till stop
      cout << endl;

      // Anropar funktionen "controlFunction" och skriver ut totalkostnaden
	  cout << endl;
	  cout << " Total samtalskostnad: "
	  << fixed << setprecision(2)
	  << controlFunction(start, stop) <<" kr" << endl << endl;

	  // Frågar om omstart
	  cout << " Ny beräkning? (j/n) ";
      char ch;
      do
      {
        ch = _getch();											// Tar emot ett tecken till "char ch"
        ch = toupper(ch);                                       // Accepterar versaler
        if (ch == 'J')                                 
	      restart = true;                                                                                                                   
        if (ch == 'N')                   
          restart = false;
		system("cls");
	  }while (!(ch == 'J' || ch == 'N'));

    }while (restart);                                            // Upprepar do...while
}
//--------------------------------------------------------------------------------------------------
// Funktionsdefinitioner
//--------------------------------------------------------------------------------------------------
// Namn: controlFunction
// Uppgift: Kontrollerar start- och stopptid
// Indata: Starttid som sträng på formen (hh:mm)
//         Stopptid som sträng på formen (hh:mm)
// Utdata: Returnerar totalkostnaden (flyttal)
//--------------------------------------------------------------------------------------------------
float controlFunction(string t1, string t2)
{ 
  // Variabler för kontroll av inmatning samt tid
  bool timeOK = true;
  int t1Hour = 0;
  int t1Minute = 0;
  int t2Hour = 0;
  int t2Minute = 0;

  do
  {
    if (!timeOK)													// Utförs vid felaktig inmatning
	{
	  cout << " Felaktig inmatning!" << endl;
	  cout << " Ange starttid (hh:mm): ";
	  cin >> t1;
	  cout << " Ange sluttid (hh:mm) : ";
      cin >> t2;
	  timeOK = true;
	}

    if (!(t1[2] == ':' && t2[2] == ':'))        // Kontrollerar att rätt tidsavgränsare används
      timeOK = false;
    
	// Skriver över ':' med mellanslag
    t1[2] = ' ';
    t2[2] = ' ';

    // Konverterar siffror i sträng till tal
    istringstream start(t1);
      start >> t1Hour >> t1Minute;
    istringstream stop(t2);
      stop >> t2Hour >> t2Minute;

    // Kontrollerar att timmar och minuter är ok
    // Kontrolleras att stopptiden är större än starttiden
    if (t1Hour < 0 || t1Hour > 23)
      timeOK = false;
	if (t2Hour < 0 || t2Hour > 23)
      timeOK = false;
    if (t1Minute < 0 || t1Minute > 59)
      timeOK = false;
	if (t2Minute < 0 || t2Minute > 59)
      timeOK = false;
    if ((t2Hour *60 + t2Minute) < (t1Hour *60 + t1Minute))
	  timeOK = false;
  }while (!timeOK);                             // Upprepas ifall tid inte är ok

  // Anropar funktionen "totalCosts" och returnerar talet med totalkostnaden
  return totalCosts (t1Hour, t1Minute, t2Hour, t2Minute);  
}
//--------------------------------------------------------------------------------------------------
// Namn: totalCosts
// Uppgift: Beräknar den totala kostnaden
// Indata: Starttid, timma (heltal)
//         Starttid, minut (heltal) 
//         Stopptid, timma (heltal
//         Stopptid, minut (heltal)
// Utdata: Returnerar totalkostnaden med moms plus eventuella rabatter (flyttal)
//--------------------------------------------------------------------------------------------------
float totalCosts(int t1Hour, int t1Minute, int t2Hour, int t2Minute)
{
  int totalMinutes = 0;
  double minutePrice = 0;
  double totalCost = 0;
  const double MOMS = 0.25;                        // Moms
  const double FULL_PRICE = 4;                     // Fullpristaxa
  const double DAY_DISCOUNT = 0.65;               // Rabatt för samtal före 8:00 och efter 18:30
  const double LONG_DISCOUNT = 0.15;              // Rabatt för samtal längre än 30 min 

  // Antar att dygnet enbart räknas i minuter, lägger på taxa till variabeln "minutePrice"
  for (totalMinutes = t1Hour *60 + t1Minute; totalMinutes < t2Hour *60 + t2Minute; totalMinutes++)
  {
    if (dayDiscount(totalMinutes))                // Anropar funktionen "dayDiscount"
	  minutePrice += (FULL_PRICE * DAY_DISCOUNT);
	else
	  minutePrice += FULL_PRICE; 
  }
  
  minutePrice += (minutePrice *MOMS);              // Adderar momsen
  totalCost = minutePrice;                         // Tilldelar totalpriset till en egen variabel
  
  // Ifall samtalet är mer än 30 min dras rabatten av från totalkostnaden
  // Totala minuterna för stopptid - totala minuterna för starttid
  if ((t2Hour *60 + t2Minute) - (t1Hour *60 + t1Minute) >30)
    totalCost -= (totalCost *LONG_DISCOUNT); 

  return totalCost;                               // Returnerar totalkostnaden
}

//--------------------------------------------------------------------------------------------------
// Namn: dayDiscount
// Uppgift: Kontrollerar ifall dygnsrabatt för given minut
// Indata: Minut för dygnet (heltal)
// Utdata: Returnerar true ifall dygnsrabatt, annars false
//--------------------------------------------------------------------------------------------------
bool dayDiscount(int minute)
{
  // Deklarerar konstanta heltal för rabatterade timmar
  const int EIGHT_AM = 480;
  const int EIGHT_THYRTY_PM = 1110; 

  // Returnerar true ifall minuterna är före 08:00 eller efter 18:30
  // 1 dygn = 24 * 60 minuter = 1440 minuter)
  return ((minute > 0 && minute< EIGHT_AM) || (minute > EIGHT_THYRTY_PM && minute < 1440)); 
}

Recommended Answers

All 19 Replies

Oh, I forgot: I also have a header file:

#ifndef labb2H
#define labb2H
  #include <iostream>
  #include <string>
  #include <sstream>   
  #include <conio.h>
  #include <ctime>                                                                         
  #include <iomanip>
  #include "iodos.h"
  using namespace std;

  void diceSim();

  void countDays();
  bool leapYear(int year);
  int daysInMonth(int month, int year);
  int daysFrom1900(int year, int month, int day);
  int days(string d1, string d2);

  void teleRate();
  float controlFunction(string t1, string t2);
  float totalCosts(int t1Hour, int t1Minute, int t2Hour, int t2Minute);
  bool dayDiscount(int minute);

#endif

Hi,

which compilation error do you get?

This is what it says:

1>c:\users\peter\documents\programvaruteknik\lab2\uppgift 4\uppgift 4\uppgift 4.cpp(30): warning C4244: 'argument' : conversion from 'time_t' to 'unsigned int', possible loss of data
1>c:\users\peter\documents\programvaruteknik\lab2\uppgift 4\uppgift 4\uppgift 4.cpp(348): warning C4244: 'return' : conversion from 'double' to 'float', possible loss of data
1>ManifestResourceCompile:
1> All outputs are up-to-date.
1>MSVCRTD.lib(crtexe.obj) : error LNK2019: unresolved external symbol _main referenced in function ___tmainCRTStartup
1>C:\Users\Peter\Documents\Programvaruteknik\Lab2\Uppgift 4\Debug\Uppgift 4.exe : fatal error LNK1120: 1 unresolved externals
1>
1>Build FAILED.

Not formatted? How do you mean?

Line 242,243,244. Use case instead of if.

switch(toupper(ch))
{
case "J"://
break;
case "N": //
break;
default: cout << "Write J/N"<<endl;
}

Your code is hard to read. Formatting makes your code makes it easier to read. For example.
Line 35:

You wrote:

resultat = rand()%6 + 
1;

Line 35
Correct:

resultat = rand() % 6 + 1;

Your comments are hard to read. Please write it in english.

Upvote my post if they helped.

Line 91. Try to explain what are you trying to do in this line?

Line 91. Try to explain what are you trying to do in this line?

Yes, I know the comments are hard to read. Sorry about that, but I haven't had time to translate into English.
Line 91 is just a kind of separator.

Line 242,243,244. Use case instead of if.

switch(toupper(ch))
{
case "J"://
break;
case "N": //
break;
default: cout << "Write J/N"<<endl;
}

I don't get it. Am I supposed to replace lines 242-244 with the code above?
I've tried it, and it generates a whole row of new problems.

I make a mistake. Replace this symbol ". Use this one '.

switch(toupper(ch))
{
case 'J'://
break;
case 'N': //
break;
default: cout << "Write J/N"<<endl;
}

Line 30.

srand((unsigned)time(0));

Why does your function on 324 return float? You are using doubles in the body of the function and then trying to cram the double (with it's additional precision back into the float). This is a warning from the compiler but it should be addressed.

Change line 30 to srand((unsigned)time(0)); to ensure that the value returned from time() is explicitly cast into an unsigned int instead of a variable of type time_t.

Your problem is that you have no main() in your code. The compiler needs to have an entry point for your program.

Sorry, but it's even further away from compiling now.
I have made the changes and my code now looks like this:

#include "MainProgram.h"
//--------------------------------------------------------------------------------------------------
// Namn:    diceSim
// Uppgift: Programmet från uppgift 1
// Indata : -
// Utdata : -
//--------------------------------------------------------------------------------------------------

void diceSim()
{
  dos_console(850);
	
  int frekvens[7] = {0, 0, 0, 0, 0, 0, 0};
  int resultat;
  int antalKast;                      

  cout << "VÄLKOMMEN TILL TÄRNINGSSIMULATORN!" << endl;				// Huvudrubrik
  cout << "==================================" << endl << endl; 
  cout << "Detta program simulerar det antal tärningskast som anges av användaren." << endl;
  cout << "Var god mata in antalet kast (1-1000): ";
  cin >> antalKast;													// Inmatning för angivna kast

  while (antalKast <= 0 || antalKast > 1000)						// Kontrollerar att värdet = 1-1000
  {
cout << "Felaktig inmatning! Försök igen: ";
    cin >> antalKast;
  }
  cout << endl;

  srand((unsigned)time(0));													// Använder systemklockan som slumpgenerator

  // Slumpar antalet kast som angivits och uppdaterar tabellen
  for (int i = 1; i <= antalKast; i++)
  {
    resultat = rand()%6 + 1;										// Får ett slumpmässigt tal 1-6
    frekvens[resultat]++;
  }

  // Skriver ut tabellen "frekvens"
  for (resultat = 1; resultat <= 6; resultat++)
  cout << resultat << ": " << setw(7) << frekvens[resultat] << endl;
  cout << endl;
  cout << "===========================================" << endl;
  cout << endl;
  
  // Skriver ut tabellen "relativ frekvens"
  cout << fixed << setprecision(2);
  cout << "Relativ frekvens för ettor: "
       << setw(5) << static_cast<float>(frekvens[1])/static_cast<float>(antalKast) << endl;
    
  cout << fixed << setprecision(2);
  cout << "Relativ frekvens för tvåor: "
       << setw(5) << static_cast<float>(frekvens[2])/static_cast<float>(antalKast) << endl;
	  
  cout << fixed << setprecision(2);
  cout << "Relativ frekvens för treor: "
       << setw(5) << static_cast<float>(frekvens[3])/static_cast<float>(antalKast) << endl;
	
  cout << fixed << setprecision(2);
  cout << "Relativ frekvens för fyror: "
       << setw(5) << static_cast<float>(frekvens[4])/static_cast<float>(antalKast) << endl;

  cout << fixed << setprecision(2);
  cout << "Relativ frekvens för femmor: "
       << setw(4) << static_cast<float>(frekvens[5])/static_cast<float>(antalKast) << endl;

  cout << fixed << setprecision(2);
  cout << "Relativ frekvens för sexor: "
       << setw(5) << static_cast<float>(frekvens[6])/static_cast<float>(antalKast) << endl;

  cout << endl;

  system("pause");
}

//--------------------------------------------------------------------------------------------------
// Namn:    countDays
// Uppgift: Programmet från uppgift 2
// Indata : -
// Utdata : -
//--------------------------------------------------------------------------------------------------
void countDays()
{  
  dos_console(850);
  bool restart;                                                 // Avgör om programmet skall upprepas
  do
  { 
    string startDate, endDate;
    system("cls");                                              // Rensar skärmen
    cout << " Detta program beräknar antalet dagar mellan två datum (tidigast 1/1 1900)" << endl;
    cout << " =========================================================================" << endl << endl;
    cout << " Ange startdatum (ÅÅÅÅMMDD): ";
    cin >> startDate;                                           // Inmatning till variabeln startDate
    cout << " Ange slutdatum (ÅÅÅÅMMDD) : ";
    cin >> endDate;                                             // Inmatning till variabeln endDate
    cout << endl;

    // Anropar funktionen days och skriver ut antalet dagar
    cout << " Antal dygn emellan = " << days (startDate, endDate) << endl << endl;

	cout << " Vill du göra en ny beräkning? (j/n)" << endl;
    char ch;
    do
    {
      ch = _getch();
      ch = toupper(ch);                                         // Fungerar med versaler
      if (ch == 'J')                                 
	    restart = true;                                                                                                                   
      if (ch == 'N')                   
        restart = false;
	}while (!(ch == 'J' || ch == 'N'));

  }while (restart);                                             // Upprepar programmet om sant
}
//--------------------------------------------------------------------------------------------------
// Funktionsdefinitioner
//--------------------------------------------------------------------------------------------------
// Namn: leapYear
// Uppgift: Kontrollerar skottår
// Indata: Årtal (heltal)
// Utdata: true/false
//--------------------------------------------------------------------------------------------------
bool leapYear(int year)
{  // Beräkning av skottår
   return year%4 == 0 && (year%100 != 0 || year%400 == 0);
}
//--------------------------------------------------------------------------------------------------
// Namn: daysInMonth
// Uppgift: Beräkna antalet dagar i en månad
// Indata: Årtal (heltal)
//         Månadsnummer (heltal)
// Utdata: Antal dagar i respektive månad, med hänsyn till skottår (heltal)
//--------------------------------------------------------------------------------------------------
int daysInMonth(int month, int year)
{
  // Innehållet 0-12 i vektorn motsvararar antalet dagar i varje månad
  int daysInMonth[13] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

  if (leapYear(year))         // Anropar funktionen leapYear
     daysInMonth[2] = 29;     // Februari får 29 dagar om skottår

  return daysInMonth[month];
}
//--------------------------------------------------------------------------------------------------
// Namn: daysFrom1900
// Uppgift: Beräkna antalet dygn från 31/12 1899 fram till ett givet datum
// Indata: År (heltal), månad (heltal), dag (heltal)
// Utdata: Antal dygn från 31/12 1899 till angivet datum (heltal)
//--------------------------------------------------------------------------------------------------
int daysFrom1900(int year, int month, int day)
{ 
  int yearsFrom1900 = 0;
  int daysFrom1900  = 0;
  int monthsDays    = 0;

  // Ökar på dagarna för året fram till angivet år
  for (yearsFrom1900 = 1900; yearsFrom1900 < year; yearsFrom1900++)
  {
    if (leapYear(yearsFrom1900))                        // Anropar funktionen leapYear
	  daysFrom1900 += 366;
	else
	  daysFrom1900 += 365;
  }

  // Ökar på dagarna för månaderna fram till angiven månad
  for (monthsDays = 0; monthsDays < month; monthsDays++)
  {
    daysFrom1900 += daysInMonth(monthsDays, year);      // Anropar funktionen "daysInMonth"
  }

  // Ökar på dagen för månaden och returnerar totalsumma
  return daysFrom1900 + day;
}
//--------------------------------------------------------------------------------------------------
// Namn: days
// Uppgift: Beräkna antalet dygn mellan två datum
// Indata: Startdatum som en sträng på formen ÅÅÅÅMMDD
//         Slutdatum som en sträng på formen ÅÅÅÅMMDD
// Utdata: Antalet dygn från startdatum till slutdatum (heltal)
//--------------------------------------------------------------------------------------------------
int days(string d1, string d2)
{ 
  // Plockar ut årtal, månad och dag med substring ur sträng d1 och d2
  string d1YearStr  = d1.substr(0,4);
  string d1MonthStr = d1.substr(4,2);
  string d1DayStr   = d1.substr(6,2);
  string d2YearStr  = d2.substr(0,4);
  string d2MonthStr = d2.substr(4,2);
  string d2DayStr   = d2.substr(6,2);

  // Omvandlar strängar till heltal
  int d1Year  = atoi(d1YearStr.c_str());
  int d1Month = atoi(d1MonthStr.c_str());
  int d1Day   = atoi(d1DayStr.c_str());
  int d2Year  = atoi(d2YearStr.c_str());
  int d2Month = atoi(d2MonthStr.c_str());
  int d2Day   = atoi(d2DayStr.c_str());

  // Anropar funktionen "daysFrom1900", returnerar sedan antalet dagar mellan datumen
  return daysFrom1900(d2Year, d2Month, d2Day) - daysFrom1900(d1Year, d1Month, d1Day);
}

//--------------------------------------------------------------------------------------------------
// Namn:    teleRate
// Uppgift: Programmet från uppgift 3
// Indata : -
// Utdata : -
//--------------------------------------------------------------------------------------------------
void teleRate()
{  
    dos_console();
    
    bool restart;                                                 // Avgör om programmet skall upprepas
    
    cout << endl;
	cout << " RingPling 2004 AB" << endl;                         // Huvudrubrik
    cout << " =================" << endl << endl;
	cout << " Beräknar samtalskostnad" << endl <<endl;

	do
	{
	  string start, stop;                                        // Sträng-variabler
	  cout << endl;
	  cout << " Ange starttid (hh:mm): ";
      cin >> start;                                              // Inmatning till start
	  cout << " Ange sluttid (hh:mm) : ";
      cin >> stop;                                               // Inmatning till stop
      cout << endl;

      // Anropar funktionen "controlFunction" och skriver ut totalkostnaden
	  cout << endl;
	  cout << " Total samtalskostnad: "
	  << fixed << setprecision(2)
	  << controlFunction(start, stop) <<" kr" << endl << endl;

	  // Frågar om omstart
	  cout << " Ny beräkning? (j/n) ";
      char ch;
      do
      {
        switch(toupper(ch))
		{
		case 'J'://
		break;
		case 'N': //
		break;
		default: cout << "Write J/N" << endl;
		}
	  }
    while (restart);                                            // Upprepar do...while
}
//--------------------------------------------------------------------------------------------------
// Funktionsdefinitioner
//--------------------------------------------------------------------------------------------------
// Namn: controlFunction
// Uppgift: Kontrollerar start- och stopptid
// Indata: Starttid som sträng på formen (hh:mm)
//         Stopptid som sträng på formen (hh:mm)
// Utdata: Returnerar totalkostnaden (flyttal)
//--------------------------------------------------------------------------------------------------
float controlFunction(string t1, string t2)
{ 
  // Variabler för kontroll av inmatning samt tid
  bool timeOK = true;
  int t1Hour = 0;
  int t1Minute = 0;
  int t2Hour = 0;
  int t2Minute = 0;

  do
  {
    if (!timeOK)													// Utförs vid felaktig inmatning
	{
	  cout << " Felaktig inmatning!" << endl;
	  cout << " Ange starttid (hh:mm): ";
	  cin >> t1;
	  cout << " Ange sluttid (hh:mm) : ";
      cin >> t2;
	  timeOK = true;
	}

    if (!(t1[2] == ':' && t2[2] == ':'))        // Kontrollerar att rätt tidsavgränsare används
      timeOK = false;
    
	// Skriver över ':' med mellanslag
    t1[2] = ' ';
    t2[2] = ' ';

    // Konverterar siffror i sträng till tal
    istringstream start(t1);
      start >> t1Hour >> t1Minute;
    istringstream stop(t2);
      stop >> t2Hour >> t2Minute;

    // Kontrollerar att timmar och minuter är ok
    // Kontrolleras att stopptiden är större än starttiden
    if (t1Hour < 0 || t1Hour > 23)
      timeOK = false;
	if (t2Hour < 0 || t2Hour > 23)
      timeOK = false;
    if (t1Minute < 0 || t1Minute > 59)
      timeOK = false;
	if (t2Minute < 0 || t2Minute > 59)
      timeOK = false;
    if ((t2Hour *60 + t2Minute) < (t1Hour *60 + t1Minute))
	  timeOK = false;
  }while (!timeOK);                             // Upprepas ifall tid inte är ok

  // Anropar funktionen "totalCosts" och returnerar talet med totalkostnaden
  return totalCosts (t1Hour, t1Minute, t2Hour, t2Minute);  
}
//--------------------------------------------------------------------------------------------------
// Namn: totalCosts
// Uppgift: Beräknar den totala kostnaden
// Indata: Starttid, timma (heltal)
//         Starttid, minut (heltal) 
//         Stopptid, timma (heltal
//         Stopptid, minut (heltal)
// Utdata: Returnerar totalkostnaden med moms plus eventuella rabatter (flyttal)
//--------------------------------------------------------------------------------------------------
float totalCosts(int t1Hour, int t1Minute, int t2Hour, int t2Minute)
{
  int totalMinutes = 0;
  double minutePrice = 0;
  double totalCost = 0;
  const double MOMS = 0.25;                        // Moms
  const double FULL_PRICE = 4;                     // Fullpristaxa
  const double DAY_DISCOUNT = 0.65;               // Rabatt för samtal före 8:00 och efter 18:30
  const double LONG_DISCOUNT = 0.15;              // Rabatt för samtal längre än 30 min 

  // Antar att dygnet enbart räknas i minuter, lägger på taxa till variabeln "minutePrice"
  for (totalMinutes = t1Hour *60 + t1Minute; totalMinutes < t2Hour *60 + t2Minute; totalMinutes++)
  {
    if (dayDiscount(totalMinutes))                // Anropar funktionen "dayDiscount"
	  minutePrice += (FULL_PRICE * DAY_DISCOUNT);
	else
	  minutePrice += FULL_PRICE; 
  }
  
  minutePrice += (minutePrice *MOMS);              // Adderar momsen
  totalCost = minutePrice;                         // Tilldelar totalpriset till en egen variabel
  
  // Ifall samtalet är mer än 30 min dras rabatten av från totalkostnaden
  // Totala minuterna för stopptid - totala minuterna för starttid
  if ((t2Hour *60 + t2Minute) - (t1Hour *60 + t1Minute) >30)
    totalCost -= (totalCost *LONG_DISCOUNT); 

  return totalCost;                               // Returnerar totalkostnaden
}

//--------------------------------------------------------------------------------------------------
// Namn: dayDiscount
// Uppgift: Kontrollerar ifall dygnsrabatt för given minut
// Indata: Minut för dygnet (heltal)
// Utdata: Returnerar true ifall dygnsrabatt, annars false
//--------------------------------------------------------------------------------------------------
bool dayDiscount(int minute)
{
  // Deklarerar konstanta heltal för rabatterade timmar
  const int EIGHT_AM = 480;
  const int EIGHT_THYRTY_PM = 1110; 

  // Returnerar true ifall minuterna är före 08:00 eller efter 18:30
  // 1 dygn = 24 * 60 minuter = 1440 minuter)
  return ((minute > 0 && minute< EIGHT_AM) || (minute > EIGHT_THYRTY_PM && minute < 1440)); 
}

What is MainProgram.h? Do this: pair one function with a main program. Get it to compile. Add the second function, get it to compile. Look in your text or on this site to see examples of programs with multiple functions.

Your code is not formatted. You need to post your comments in english.
Line 282.

you wrote:

if(!(t1[2] == ':' && t2[2] == ':'))

Correct:

if (t1[2] != ':' && t2[2] != ':'))

Line 332.Delete line 323

for (int totalMinutes = t1Hour *60 + t1Minute; totalMinutes < t2Hour *60 + t2Minute; totalMinutes++)

The OP is correct, he/she wants to make sure that if either of the times doesn't have a colon, the time is bad.

!(A && B) is equivalent to !A || !B by DeMorgan's law(theorem, whatever)

Line 107-110

switch(toupper(ch))
{
case 'J'://
break;
case 'N': //
break;
default: cout << "Write J/N"<<endl;
}

Line 241-249. You forgot to write the code. I wrote an example in the first page.
Correct your mistakes.

Line 107-110

switch(toupper(ch))
{
case 'J'://
break;
case 'N': //
break;
default: cout << "Write J/N"<<endl;
}

alexchen, I know you're trying to help, but please stop and think. This block was perfectly fine before.

ch = toupper(ch); 
        if (ch == 'J')                                 
	      restart = true;                                                                                                                   
        if (ch == 'N')                   
          restart = false;

All you've done is change two if's to a switch and forgotten to add the actual code to be executed for each. In other words, you took something that worked and made it not work. I'm not trying to be harsh here, but that's what you did.

It was an example. This symbol (//) means your code.

switch(toupper(ch))
{
case 'J':restart = true;   
break;
case 'N': restart = false;
break;
default: cout << "Write J/N"<<endl;
}

This error arrives when the linker is not able to find the main function()...
Adding a main() function to your code will solve your problem

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.