-1
#include <iostream>

using namespace std;

template<class T>
class Array{
public:
    T U[10];

    friend void DataOut(Array<string>);
    friend void GetData(Array<string>);
};

void DataOut(Array<string> Array1){
    cout << Array1.U[0];
}

void GetData(Array<string> Array1){
    cin >> Array1.U[0];
    cin.clear();
}

int main(){
    Array<string> Arr1;
    GetData(Arr1);
    DataOut(Arr1);
}

I made a class template and created two functions: GetData for entering string and DataOut for printing that string, but after entering string it doesn't print it. What have I done wrong?

Toby Speight
  • 27,591
  • 48
  • 66
  • 103
Dazai
  • 1
  • 1

1 Answers1

1

I placed comments where I made changes. The main fix is to pass your object by reference, especially to Getdata(). You passed a copy, put data into the copy, and when the function ended, the copy goes away and your original object was never touched.

#include <iostream>

using namespace std;

template <class T>
class Array {
 public:
  T U[10];

  friend void DataOut(
      const Array<string>&);  // CHANGED: Need to take object by reference
  friend void GetData(Array<string>&);  // SAME
};

void DataOut(const Array<string>& Array1) {  // SAME
  cout << Array1.U[0];
}

void Getdata(Array<string>& Array1) {  // SAME
  cin >> Array1.U[0];
  // cin.clear();  // CHANGED: Why?
}

int main() {
  Array<string> Arr1;
  Getdata(Arr1);
  DataOut(Arr1);
}
sweenish
  • 4,793
  • 3
  • 12
  • 23
  • 1
    Why? To clear out the data left in the stream of course! Why else would you call a function named `clear`? To clear error flags? – user4581301 May 14 '21 at 20:46
  • 1
    @user4581301: Clearing error flags is what it does, if you want to flush the remaining data that would be `ignore` – Ben Voigt May 14 '21 at 20:59
  • It seems unnecessary here is what I was intending. I know what it does. – sweenish May 15 '21 at 01:52