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
Related
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <errno.h>
int main(int argc, char *argv[]) {
static char words[540000][25];
FILE *file;
int i, j;
size_t cnt, n;
char word[25];
srand(time(NULL));
file = fopen("/storage/emulated/0/Projects/RWord.txt", "r");
if (file == NULL){
printf("The file cannot be opened.\n");
perror(file);
return 1;{}
}
cnt = 0;
while(1==fscanf(file, "%24s", word)){
if(cnt == 540000)
break;
strcpy(words[cnt++], word);
}
fclose(file);
n = cnt;
if(n > RAND_MAX){
int part;
size_t random = 0;
i = n / RAND_MAX;
part = rand() % (i+1);
if(part == i){
j = n % RAND_MAX;
if(j != 0)
random = random + RAND_MAX*part + rand() % j;
else
random = random + RAND_MAX*(part-1) + rand();
} else {
random = random + RAND_MAX*part + rand();
}
printf("%s\n", words[random]);
} else {
int random = rand() % n;
printf("%s\n", words[random]);
}
return 0;
}
Note: It is a bit weird but I am trying this code on mobile.
I am getting this error: No such file or directory.
I used perror() and got the specific error. I want to print a random word from the text file but I can't get the code to read the f
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;
}
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;
}
So my decrypter program seems to not be able to find the key and implement it by itself. I noticed that if I changed the key to equal -5 which is the correct key it would print out the decrypted text correctly. However I am unable to figure out how to make the program figure it out by itself without having me to put it in manually. Any help would be greatly appreciated! Thank you!
rotUtils.h
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include "rotUtils.h"
int rotate(int c, int n){
if (n == 0) return c;
int nRot = abs(n) % (RANGECHAR + 1);
if(n > 0)
return rotatePlus(c + nRot);
else
return rotateMinus(c - nRot);
}
int rotatePlus(int sum){
int diff = sum - MAXCHAR;
if (sum > MAXCHAR) sum = MINCHAR + diff - 1;
return sum;
}
int rotateMinus(int sum){
int diff = MINCHAR - sum;
if (sum < MINCHAR) sum = MAXCHAR - diff + 1;
return sum;
}
decrypt.cpp
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include "rotUtils.h"
bool solved( char decodearr[], char dictarr[][30], int size1, int size2){
char* compared;
bool result = false;
for(int j = 0; j < size2; j++){
compared = strstr( decodearr, dictarr[j]);
}
if( compared != '\0'){
result = true;
}
return result;
}
int decode( char codearr[], char dictarr[][30], int size1, int size2)
{
bool solution = false;
int key = -50; This is where I had to change it to -5 to solve
char decodearr[10000];
while(solution == false && key < 51)
{
for( int i = 0; i < size1; i++)
{
if(!isspace(codearr[i]))
{
decodearr[i] = rotate(codearr[i], key);
}
else
decodearr[i] = codearr[i];
}
solution = solved( decodearr, dictarr, size1, size2);
if( solution == false)
{
key++;
}
}
for( int j = 0; j < size1; j++)
{
codearr[j] = decodearr[j];
}
return key;
}
int main( int argc, char* argv[])
{
char* file = argv[1];
char* dictionary = argv[2];
char code[10000];
char dict[30000][30];
FILE* codeFile;
codeFile = fopen(file, "r");
int i = 0;
int j = 0;
int key;
FILE* dictFile;
dictFile = fopen(dictionary, "r");
while(!feof(codeFile))
{
code[i] = fgetc(codeFile);
i++;
}
code[ i ]= '\0';
fclose(codeFile);
while(!feof(dictFile))
{
fscanf(dictFile, "%s", dict[j]);
j++;
}
key = decode(code, dict, i, j);
fclose(dictFile);
for(int k = 0; k < i; k++)
{
printf("%c", code[k]);
}
printf( "\nThe key is: %d\n", key);
return 0;
}
Solved() will only return true if there is a match on the last dictionary word currently, you have to move that check inside. You could print to screen whenever you find a key that has a match on your dictionary and/or keep a list of possible keys then print after you are done with them all, right now you would exit as soon as you find any match even if it was just luck.
Hello I am taking an intro to C-programming class so I am using very basic codes. Here I am simply trying to get a matrix of the commas out of the main string. However when I try running the program it keeps crashing on me and I don't know what is my problem. I was able to use the fgets function correctly so I think that is working fine still.
CD Data.txt File
Eagles, Hotel California, 1976, Rock, 4
The Fratellis, Costello Music, 2006, Garage Rock, 5
Awolnation, Megalithic Symphony, 2011, Indie Rock, 5
Lindsey Stirling, Lindsey Stirling, 2012, Classical Crossover, 5
Arctic Monkeys, AM, 2013, Indie Rock, 4
Program
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define row 1000
#define column 1000
void getCommas(char str[], int commas[])
{
int flag, count, index;
count = 0;
index = 0;
flag = 1;
while(flag = 1)
{
if(str[count] = ',')
{
commas[index] = count;
index = index + 1;
}
count = count + 1;
if(str[count] = '\0')
{
flag = 0;
}
}
}
int main()
{
int i;
char CdInfo[row][column];
int Index[row][column];
FILE *fp;
fp = fopen("CD Data.txt","r");
for(i=0; i<5; i++)
{
fgets(CdInfo[i], sizeof CdInfo, fp);
//printf("%s\n",CdInfo[i]);
}
for (i=0; i<5; i++)
{
getCommas(CdInfo[i], Index[i]);
}
fclose(fp);
return 0;
}
These two variables are too big to be on the stack:
int main()
{
int i;
char CdInfo[row][column]; //<<
int Index[row][column]; //<<
declare them as static or as global variables.
And:
while(flag = 1)
should be
while(flag == 1)
and all
if (str[count] = ...
should be
if(str[count] == ...
You should also think about replacing
while(flag = 1) {
with :
while(flag == 1)
// note:
// the code is not making any use of more than one line of the
// input file at any one time, so
// only the current row actually needs to be defined
// note:
// this code makes no check for max length of each row (1000 char)
// that could/will be a problem when the input line is longer than 1000 character
// to avoid the error of writing an assignment rather than a literal,
// place the literal on the left side,
// then the compiler will notify you of the error
// rather than you having to spend time debugging the code
// trying to find the error
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define row 1000
#define column 1000
//void getCommas(char str[], int commas[])
void getCommas( char * pStr, int * pCommas )
{
//int flag, count, index;
//count = 0;
//index = 0;
//flag = 1;
int flag = 1;
int count = 0;
int index = 0;
//while(flag = 1)
// following while loop could eliminate
// the 'flag' variable and related code by using
// and would be safer because never looking at string termination
// character but once.
// while( '\0' != pStr[count] )
while( 1 == flag )
{
//if(str[count] = ',')
if( ',' == pStr[count] )
{
pCommas[index] = count;
index = index + 1;
}
count = count + 1;
//if(str[count] = '\0')
if( '\0' == pStr[count] )
{ // then found end of string
flag = 0;
}
}
}
char CdInfo[row][column];
int Index[row][column];
int main()
{
int i = 0;
int rowCount = 0;
//char CdInfo[row][column]; // this is a huge item on the stack,
//int Index[row][column]; // this is a huge item on the stack,
//FILE *fp;
FILE *fp = NULL;
fp = fopen("CD Data.txt","r");
// always check the result of calls to io functions
if ( NULL == fp )
{ // then fopen failed
perror( "fopen" );
exit(1);
}
// implied else
// there is no reasonable reason (in the real world)
// to expect the input to be only 5 lines
//for(i=0; i<5; i++)
//{
// fgets(CdInfo[i], sizeof CdInfo, fp);
// //printf("%s\n",CdInfo[i]);
//}
for( i=0; i<row; i++ )
{
// following line checks results of call to I/O function
if( 0 == fgets( CdInfo[i], row, fp ) ) { break; }
// above line exits loop on end of file or I/O error
rowCount++;
}
//for (i=0; i<5; i++)
for( i = 0; i < rowCount; i++ )
{
getCommas(CdInfo[i], Index[i]);
}
fclose(fp);
return 0;
}