生成两个随机字符连接它们并将它们存储在二维数组C中

时间:2017-04-25 16:15:32

标签: c arrays multidimensional-array

我想生成两个随机字符(或一串两个随机字符),将它们连接成一个字符串并将其存储在一个二维数组中。

有谁知道为什么这不起作用? (我知道代码并不是特别好,但我想你必须从某个地方开始)。感谢。

randomvar = rand() % 26;
strncpy(AircraftRandomLetter1[LocalCallCount], alphabet, randomvar);
AircraftRandomLetter1[LocalCallCount + 1] = '\0';
randomvar = rand() % 26;
strncpy(AircraftRandomLetter2[LocalCallCount], alphabet, randomvar);
AircraftRandomLetter1[LocalCallCount + 1] = '\0';
strncat(AircraftRandomLetter2[LocalCallCount], 
AircraftRandomLetter1[LocalCallCount], sizeof(AircraftRandomLetter1));


fputs(AircraftRegisterRequestingTakeOffIdentifer[LocalCallCount], 
fileObject);
// Print result to file

回答chux,这有点朝正确的方向吗? :

{{1}}

1 个答案:

答案 0 :(得分:0)

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int TimeTracking(void);
int PrinterFunction (void);

int main() {

  PrinterFunction ();

  return EXIT_SUCCESS;
}

int TimeTracking(void) {
  static unsigned int call_count = 0; // At first it has never been called
  call_count++;

  return call_count;
}

int PrinterFunction (void) {
  int LocalCallCount = TimeTracking();
  int randomvar = 0;

  short i;

  char MasterArray[1440][10];
  /*
    +1 because we have to reserve a cell for «\0».
    The arrays must be initialized in order to have «\0» so we will
    not have to deal with it later.

    Find out more about strings here https://www.tutorialspoint.com/cprogramming/c_strings.htm
  */
  char AircraftRandomLetter1[11] = {0};
  char AircraftRandomLetter2[11] = {0};

  /*
     You did not specify a type...
     Just in case : https://linux.die.net/man/3/fopen
  */
  FILE * fileObject = fopen("Default.txt", "a");

  /*****
        I want to generate two random chars (Or a string of two random chars),
        concatenate them into a string and store it in a 2D array.
  *****/

  /*
    You have to specify a «seed» or else you will generat the same pseudo-random
    number.
    RTM : https://linux.die.net/man/3/srand
  */
  srand(time(NULL)); // You only need to call it once.
  for (i = 0; i < 10; ++i) { // Genarate 10 random numbers
    randomvar = rand() % 26;
    AircraftRandomLetter1[i] = 'A' + randomvar;

    randomvar = rand() % 26;
    AircraftRandomLetter2[i] = 'A' + randomvar;
  }

  /*
    Add the randomly ganerated string to MasterArray at position LocalCallCount.

    I'm not sure that's what you intend to do...
    If that's not the case you should be able to take it from here :)
   */
  strcat(MasterArray[LocalCallCount], AircraftRandomLetter1);
  strcat(MasterArray[LocalCallCount], AircraftRandomLetter2);
  printf("%s", MasterArray[LocalCallCount]);

  /*
    Write the results...

    Read about fprintf here -> https://linux.die.net/man/3/fprintf
  */
  fprintf(fileObject, "%s\n", MasterArray[LocalCallCount]);

  fclose(fileObject);

  return EXIT_SUCCESS;
}