T
T
Themidis Koudes2020-05-07 14:48:53
C++ / C#
Themidis Koudes, 2020-05-07 14:48:53

How to deal with an array of strings in c, c++?

bool in_list(char *l1[],char *l2,int kolvo) {
      int i;
      for (i = 0; i < kolvo; i++) {
        if (strcmp(l1[i], l2) == 0) {
          return true;
        }
      }
      return false;
    }
int func(){
                FILE *f;
    int nom;
    char gr[8];
    char fam[12];
    int oc[3];;
    int k=0,i;
    char *f_n;
    char  *grps[] = {""};

    f_n = (char*)(void*)Marshal::StringToHGlobalAnsi(openFile1->FileName->ToString());
    f = fopen(f_n, "r");
    while (fscanf(f,"%d",&nom)!=EOF) {
      fscanf(f, "%s%s", gr,fam);
      for (i = 0; i < 3; i++) fscanf(f, "%d", &oc[i]);
      if (!(in_list(grps, gr, k))) {
        grps[k] = new char[8];
        strcpy(grps[k],gr);
        k++;
        String ^p = gcnew String(gr);
        this->comboBox1->Items->Add(p);

      }
      String^ st = gcnew String("");
      String ^q = gcnew String(gr);
      String ^p = gcnew String(fam);
      st = st + nom;
      if (st->Length == 1)
        st = " " + st;
      st = st + "  " + q + "  " + p + "  " + oc[0] + "  " + oc[1]
        + "  " + oc[2] + "\n";
      this->richTextBox1->AppendText(st);

    }
    fclose(f);
    //f = fopen(f_n, "r");
    //fclose(f);
  }
  else
    MessageBox::Show("Ошибка открытия файла");
  flag = 0;
}

It is necessary to make sure that all gr are collected in grps, moreover, once each, create a list of groups.
But it turns out that only the first gr is stored in grps, and subsequent ones are not recorded.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
J
jcmvbkbc, 2020-05-07
@Femid

char *grps[] = {""};
But it turns out that only the first gr is stored in grps, and the subsequent ones are not written.

Do you understand that you have a single element in the grps array, and the recording of all elements after the first one goes past this array, somewhere on the stack, spoiling other data?
grps[k] = new char[8];
...
String^ st = gcnew String("");

And if your question is not about C, then correct the tags.

D
Daniil Demidko, 2020-05-07
@Chronicler

Use andstd::stringstd::vector

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question