I am trying to print to the screen randomly in C. I am using random and time to generate random index and printing it but It definetely is not the way to do it. How do I print every element randomly to the screen in c?
Here is the code I have so far.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#define leng 128
#define arr 10
int main(void)
{
char line[arr][leng];
char fname[20];
FILE *fptr = NULL;
int i = 0;
int tot = 0;
scanf("%s",fname);
fptr = fopen(fname, "r");
while(fgets(line[i], leng, fptr))
{
line[i][strlen(line[i]) - 1] = '\0';
i++;
}
srand(time(0));
for(int i = 0; i < 6; ++i)
{
printf("%s\n", line[rand()%10]);
}
return 0;
}
My random text file has 6 lines of code.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#define LEN 128 //Don't mind the capital, personal preference for defines
#define ARR 6 //Make this match the number of lines in your file
int main(void)
{
char line[ARR][LEN];
char fname[20];
int test[ARR] = {0}; //Added an array to test if index already created
int ind[ARR] = {0}; //Array to store index created randomly
int ind_done = 0; //Counter for index array
FILE *fptr = NULL;
int i = 0;
int tot = 0;
scanf("%s",fname);
fptr = fopen(fname, "r");
while(fgets(line[i], LEN, fptr))
{
line[i][strlen(line[i]) - 1] = '\0';
i++;
}
srand(time(0));
for(int i = 0; i < ARR; ++i)
{
printf("%s\n", line[rand()%ARR]);
}
//Keep creating indexes using rand till all unique indexes are created
while (ind_done<ARR) {
int i = rand()%ARR;
if (test[i] == 0) {
ind[ind_done] = i;
ind_done++;
test[i] = 1;
}
}
for(int i = 0; i < ARR; ++i)
{
printf("%s\n", line[ind[i]]);
}
return 0;
}
Related
I am working with a code that generates a fixed number of files and keeps that number. After every new file is created, an old one has to be deleted. This is the code:
#include <stdio.h>
#include <stdlib.h> // needed for malloc
#include <string.h> // needed for strcpy
#include <unistd.h>
#define Extension ".txt"
#define LOG_MIN_FILENAME_SIZE 32
#define NBR_OF_FILES 6
char buffer[LOG_MIN_FILENAME_SIZE];
int timez = 0;
int minutes = 0;
int count = 0;
FILE* pf = NULL;
char* ListOfFiles[6];
int main(void)
{
for (int i = 0; i < 3; i++) {
ListOfFiles[i] = calloc(LOG_MIN_FILENAME_SIZE + 1, 1);
}
for (int i = 0; i < 10; i++) {
sprintf(buffer, "%d" "%d" Extension, minutes, timez);
if (access(buffer, F_OK) == -1) {
pf = fopen(buffer, "w"); // create the file
count++;
fclose(pf); //closing the files is necessary
if (count >= NBR_OF_FILES) {
remove(ListOfFiles[0]); //remove the oldes file.
}
for (int i = 0; i < NBR_OF_FILES - 1; i++) {
strcpy(ListOfFiles[i], ListOfFiles[i + 1]); // u cant use just normal assignment because it copies the head ot the pointer rather than the actual content of it
}
strcpy(ListOfFiles[NBR_OF_FILES - 1], buffer);
}
timez++;
minutes++;
}
for (int i = 0; i < NBR_OF_FILES - 1; i++) {
printf("%s", ListOfFiles[i]);
}
}
In the output, I get only one file created at a time (with every execution). When I execute the program more than NBR_OF_FILE times, no files are deleted! Do you have any idea that what the issue could be?
I wanna store an array of Strings and display it like this
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main () {
int i = 0;
char* array[200000];
char prod [10];
FILE * fp = fopen ("arrayValues.txt", "r");
while (fgets(prod, 10, fp) != NULL) {
array[i] = strtok(prod, "\n\r");
i++;
}
fclose(fp);
for (i = 0; array[i] ; i++) {
printf("%s %d\n", array[i], i);
}
}
but the output is only the last line of the file im working with x times.
Suggestions?
Using your coding style try this (please adjust the hard coded values to your needs)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main () {
int i = 0, j = 0;
char array[200000][11];
char prod [10];
char *ptr;
memset(array, 0, sizeof(array));
FILE * fp = fopen ("arrayValues.txt", "r");
while (fgets(prod, 10, fp) != NULL) {
ptr = strtok(prod, "\n\r");
snprintf(array[i], sizeof(array[i]) , ptr);
printf("%s\n", array[i]);
i++;
}
fclose(fp);
printf("============\n");
for (j = 0; j < i; j++){
printf("%s %d\n", array[j], j);
}
return 0;
}
I am having trouble making an array equal another array in c.
in the main method it will not let me assign inputInt1 to the returned value of converTwosComp.
#include <stdio.h>
#include <stdlib.h>
int validChecker(char *input_StringIn);
int* convertTwosComp(char *inputStringIn, int *inputIntIn);
int main(void) {
char inputString1[11];
char inputString2[11];
int inputInt1[11];
int inputInt2[11];
printf(" is ");
inputInt1 = convertTwosComp(inputString1, inputInt1);
for(i = 0; inputString1[i]; i++){
printf("%d", inputInt1[i]);
}
int * convertTwosComp(char *inputStringIn, int *inputIntIn){
int digit;
int i;
if((inputStringIn[0] == '+') ||(inputStringIn[0]) == '0'){
inputStringIn[0] = 0;
}
if(inputStringIn[0] == '-'){
inputStringIn[0] = 1;
}
for(i = 0; inputStringIn[i]; i++){
digit = inputStringIn[i] - '0';
inputStringIn[i] = digit;
}
for(i = 0; inputIntIn[i]; i++){
if(inputIntIn[i] == 0){
inputIntIn[i] = 1;
}
if(inputIntIn[i] == 1){
inputIntIn[i] = 0;
}
}
return inputIntIn;
}
in the main method it will not let me assign inputInt1 to the returned value of converTwosComp.
This is what you probably need:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void){
char array1[] = "Michi";
size_t len = strlen(array1);
char *array2 = malloc(len+1);
memcpy(array2, array1, len+1);
printf("Array2 = %s\n",array2);
free(array2);
return 0;
}
Output:
Array2 = Michi
You can always use a for loop to copy a string, in case you do not want to use memcpy.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
char one[30];
char two[30];
while(fgets(one,sizeof(one),stdin))
{
int len = strlen(one);
for(int i = 0; i < (len + 1); i++)
{
two[i] = one[i];
}
printf("%s", two);
break;
}
return EXIT_SUCCESS;
}
This file needs to read a text file with numbers on each line, and preload the values from the text file into myArray. It also needs to read the integer for arraySize, so that it can be used to calculate the mean and median. The code is in c, but the teacher uses c++ file names and doesn't want us t change it. I also want to total the numbers, but when executed it doesn't print anything.
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include "Utils.cpp"
int main(void)
{
//declare variables
int myArray[]={};
// declare a string to hold the name of the file
// that will be read into your statsArray
char statsFile[] = "2005.txt"; /* file to be read in */
int arraySize = getFileSize(statsFile); /* determine size of file */
//dynamically declare statsArray based on size of file
int *statsArray = (int*)malloc(sizeof(int)*arraySize);
// initialize arrays with zero values
initializeArray(myArray, arraySize);
//load array from file
loadArray(myArray, arraySize, statsFile);
// sum stats array
int total=0;
for(int x=0;x<myArray[arraySize-1];x++){
total+=myArray[x]; //adds each element of array to total
}
printf("%i",total);
Here is the utils.cpp that was provided.
#include <stdio.h>
int getFileSize(char fileName[])
{
FILE *fr; /* declare the file pointer */
int c; /*Nb int (not char) for the EOF */
int newlineCount = 0;
// open the file to count the lines
fr = fopen(fileName, "rt");
// count the newline characters
while ( (c=fgetc(fr)) != EOF)
{
if (c =='\n')
newlineCount++;
}
return newlineCount;
}
void loadArray(int list[], int size, char fileName[])
{
FILE *fr; // declare the file pointer
int count = 0; // running line count
char line[80];
fr = fopen(fileName, "rt");
while(fgets(line, 80, fr) != NULL)
{
// get a line, p to 80 chars fr. done if NULL
sscanf(line, "%i", &list[count]);
count++;
}
}
void initializeArray(int list[], int size)
{
for (int i = 0; i < size; i++)
{
list[i] = 0;
}
}
void sortArray(int list[], int size)
{
int tempNumber;
for (int i = 0; i < size; i++)
{
for (int j = i +1; j < size; j++)
{
if(list[i] > list[j])
{
tempNumber = list[i];
list[i] = list[j];
list[j] = tempNumber;
}
}
}
}
i have below code, that i expect should read text from file, store words in array and then print it out in random order. Final array is int, but should be char and it does not give me proper answer.
#include<stdio.h>
#include<string.h>
#include <stdlib.h>
#include <time.h>
int main()
{
char message[10][150], buffer[150];
int i = 0;
int cntr = 9;
char freeArray[9];
srand(time(NULL));
freeArray[i] = rand() % cntr;
FILE *file_in;
file_in = fopen("test.txt", "r");
while (fgets(buffer, 150, file_in))
{
i = rand() % cntr;
strcpy(message[freeArray[i]], buffer);
}
while (cntr >= 0)
{
i = rand() % cntr;
strcpy(message[freeArray[i]], buffer);
freeArray[i] = freeArray[cntr--];
printf("%s", freeArray[i]);
}
return 0;
}
I have alternative code, but this one gives me text without shuffle.
#include<stdio.h>
#include<string.h>
#include <stdlib.h>
#include <time.h>
int main()
{
/*declare and initialise variable*/
char message[10][150],buffer[150];
int i=0;
int j;
srand(time(NULL));
FILE *file_in;
file_in=fopen("test.txt", "r");
/*stores and prints the data from the string*/
while(fgets(buffer,150,file_in)){
strcpy(message[i],buffer);
}
while(i < 10)
{
j = rand() % 10;
printf("%s\n",message[j]);
i++;
}
return 0;
The following code:
-- compiles cleanly
-- contains all the changes needed to the OPs posted code
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
#define MAX_MESSAGES (10)
#define MAX_MESSAGE_LEN (150)
static char message[MAX_MESSAGES][MAX_MESSAGE_LEN] = {{'\0'}};
static char buffer[MAX_MESSAGE_LEN] = {'\0'};
int main()
{
/*declare and initialise variable*/
int i=0;
int j;
FILE *file_in;
if( NULL == (file_in=fopen("test.txt", "r") ) )
{ // then, fopen failed
perror( "fopen failed for test.txt" );
exit( EXIT_FAILURE );
}
// implied else, fopen successful
srand(time(NULL));
/*stores and prints the data from the string*/
while( (i<MAX_MESSAGES) && fgets(buffer,150,file_in) )
{
strcpy(message[i],buffer);
i++;
} // end while
printf("\ndisplay %d messages in random order\n", MAX_MESSAGES);
printf("with possible repeated messages and skipped messages\n");
for( i=0; i < MAX_MESSAGES; i++)
{
j = rand() % MAX_MESSAGES;
printf("message: %d: %s\n",j, message[j]);
} // end for
return 0;
} // end function: main
The following is to answer the question given in an answer block
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
//#include <time.h>
#define MAX_MESSAGES (10)
#define MAX_MESSAGE_LEN (150)
static char message[MAX_MESSAGES][MAX_MESSAGE_LEN] = {{'\0'}};
static char buffer[MAX_MESSAGE_LEN] = {'\0'};
static char t[MAX_MESSAGE_LEN] = {'\0'};
int main()
{
/*declare and initialise variable*/
int i=0;
int j = 0;
FILE *file_in = NULL;
if( NULL == (file_in=fopen("test.txt", "r") ) )
{ // then, fopen failed
perror("fopen for test.txt failed");
exit( EXIT_FAILURE );
}
// implied else, fopen successful
/*stores, sorts and prints the data from the string*/
i = 0;
while( (i<10) && (fgets(buffer,150,file_in)) )
{
strcpy(message[i],buffer);
i++;
} // end while
for (i = 1; i < 3; i++)
{
for (j = 1; j < 3; j++)
{
if (strcmp(message[j - 1], message[j]) > 0)
{
strcpy(t, message[j - 1]);
strcpy(message[j - 1], message[j]);
strcpy(message[j], t);
} // end if
} // end for
} // end for
printf("\nStrings in order are : ");
for (i = 0; i < 3; i++)
{
printf("message: %d: %s\n", i+1, message[j]);
} // end for
getchar();
return 0;
} // end function: main