Hello, I have to implement an overloading insertion and extraction. My fields are char, char and float.
I met some problems with data types. How can I use overloading insertion/extraction with strings? Can You state the mistakes in my code? Thanks

// laba8pop.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "iostream"
using namespace std;

class City {

    public:
      char city;
      char country;
      float population;

    public:

        City(){
            city = ' ';
            country = ' ';
            population = 0.0;
        }

        City(char ci, char co, float pe)
        {
            city = ci;
            country = co;
            population = pe;
        }

        friend ostream &operator<<( ostream &output, const City &C )
        { 
            output << C.city << " - " << C.country << " - " << C.population << " millions.";
            return output;            
        }

        friend istream &operator>>( istream  &input, City &C )
        { 
            input >> C.city >> C.country >> C.population;
            return input;            
        }

};

int main()
{
    City C1("Kyiv", "Ukraine", 5.4), C2("London", "England", 6.7), C3;

    cout << "Enter the value of objects : " << endl;
    cin >> C3;

    cout << C1 << endl;
    cout << C2 << endl;
    cout << C3 << endl;

    return 0;
}

THe class variable named city is a char. A single char. It can hold one letter. Just one. It cannot hold Kyiv, because Kyiv is four letters. Change it to a string.

THe class variable named country is a char. A single char. It can hold one letter. Just one. It cannot hold Ukraine, because Ukraine is seven letters. Change it to a string.

If you want to store a string, use a string. Not a char.

Edited 2 Years Ago by Moschops

This article has been dead for over six months. Start a new discussion instead.