-3

I try to create a program for football match with array in cpp

#include <iostream>
#include <string>

using namespace std;

// Struct untuk tim
struct Tim {
  string nama_tim;
  int skor;
};

// Fungsi untuk menampilkan hasil pertandingan
void tampilkan_hasil(Tim tim[], int jumlah_tim) {
  cout << "Hasil pertandingan: " << endl;
  for (int i = 0; i < jumlah_tim; i++) {
    cout << tim[i].nama_tim << ": " << tim[i].skor << " gol" << endl;
  }
}

// Fungsi untuk menentukan pemenang
void tentukan_pemenang(Tim tim[], int jumlah_tim) {
  int index_tim_pemenang = 0;
  for (int i = 0; i < jumlah_tim; i++) {
    if (tim[i].skor > tim[index_tim_pemenang].skor) {
      index_tim_pemenang = i;
    }
  }
  cout << "Pemenangnya adalah " << tim[index_tim_pemenang].nama_tim << endl;
}

int main() {
  // Masukkan jumlah tim
  static const int jumlah_tim;
  cout << "Masukkan jumlah tim: ";
  cin >> jumlah_tim;

  // Buat array tim
  Tim tim[jumlah_tim];

  // Masukkan data tim
  for (int i = 0; i < jumlah_tim; i++) {
    cout << "Masukkan nama tim ke-" << i + 1 << ": ";
    cin >> tim[i].nama_tim;
    cout << "Masukkan skor tim ke-" << i + 1 << ": ";
    cin >> tim[i].skor;
  }

  // Tampilkan hasil pertandingan
  tampilkan_hasil(tim, jumlah_tim);

  // Tentukan pemenang
  tentukan_pemenang(tim, jumlah_tim);

  return 0;
}

The First Error : "no operator ">>" matches these operands " [LN 35]

cin >> jumlah_tim;

Second Error : "expression must have a constant value" [LN 38]

Tim tim[jumlah_tim];

it should contain the user input to array data

273K
  • 29,503
  • 10
  • 41
  • 64
Irfan Saf
  • 3
  • 5

1 Answers1

1

Two errors

  1. If a variable is constant then (obviously) you cannot change it. And if a variable cannot be changed then you cannot read into that variable using >>.

  2. Array sizes must be compile time constants in C++. Since the size of an array must be known to the compiler, you cannot read the size of an array from cin.

The solution to your problems is to use a vector. Vector sizes do not have to be constants in C++.

#include <vector>

// Masukkan jumlah tim
int jumlah_tim;
cout << "Masukkan jumlah tim: ";
cin >> jumlah_tim;

// Buat vector tim
vector<Tim> tim(jumlah_tim);

Obviously once you change tim to be a vector further changes are needed to the rest of your code. For example

void tampilkan_hasil(const vector<Tim>& tim) {
    cout << "Hasil pertandingan: " << endl;
    for (size_t i = 0; i < tim.size(); i++) {
        cout << tim[i].nama_tim << ": " << tim[i].skor << " gol" << endl;
    }
 }
john
  • 85,011
  • 4
  • 57
  • 81