Reputation: 17
I'm doing a school project and I'm having a lot of difficult with it. Currently I'm working on two functions and struct. The first function should randomly generate a line from a file(a movie is stored on each line) and then the second function should replace all the characters with asterisks like a hangman game. The struct should store the normal film title and the hidden one from each function.
I can't see where I'm going wrong here if anyone could see an error? The program compiles okay but when I run the program it does nothing?
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
typedef struct {
char title[50];
char hidden[50];
}Title;
void Film(Title t){
FILE *fopen(), *fp;
fp = fopen("Film.txt", "r");
int i=0;
int number;
char movies[44][50];
while( i<45 ){
fgets(movies[i], sizeof(movies[i]), fp);
i++;
}
srand(time(NULL));
number = (rand() % 44);
//strcpy(t.title[50], movies[number]);
movies[number] == t.title[50];
printf("%s", t.title);
return;
fclose(fp);
}
char Star(Title t){
int val;
char c;
int lenMovie;
printf("%s", t.title);
lenMovie = strlen(t.title);
//strcpy(t.hidden, t.title[50]);
t.title[50] == t.hidden[50];
for(val=0; val <= lenMovie; val++)
{
c = t.hidden[val];
if(c >= 'a' && c<= 'z'){
printf("*");
t.hidden[val] = '*';
}
else if(c >= 'A' && c<= 'Z'){
printf("*");
t.hidden[val] = '*';
}
else{
printf("%c", c);
t.hidden[val] = c;
}
}
printf("%s", t.hidden);
return 0;
}
int main(){
Title t;
Film (t);
Star (t);
}
Upvotes: 1
Views: 71
Reputation: 64672
Here's a cleanup of most of the screwups:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
typedef struct {
char title[50];
char hidden[50];
}Title;
void Film(Title* pT)
{
int i=0;
int number;
char movies[44][50];
FILE *fp = NULL;
fp = fopen("Film.txt", "r");
for(i=0; i<44; ++i)
{
fgets(movies[i], sizeof(movies[i]), fp);
}
fclose(fp);
number = (rand() % 44);
strcpy(pT->title, movies[number]);
printf("%s", pT->title);
}
char Star(Title* pT)
{
int val;
char c;
int lenMovie;
printf("%s", pT->title);
lenMovie = strlen(t->title);
strcpy(pT->hidden, pT->title]);
for(val=0; val <= lenMovie; val++)
{
c = t.hidden[val];
if(c >= 'a' && c<= 'z')
{
printf("*");
pT->hidden[val] = '*';
}
else if(c >= 'A' && c<= 'Z')
{
printf("*");
pT->hidden[val] = '*';
}
else
{
printf("%c", c);
pT->hidden[val] = c;
}
}
printf("%s", pT->hidden);
}
int main(){
Title t;
srand(time(NULL));
Film (&t);
Star (&t);
}
Upvotes: 1
Reputation: 3681
In C, structs are passed by value, so Film(t)
and Star(t)
each operate on their own independent copy of t
. The struct t
that is being copied is uninitialized, so when Star()
goes to read from its fields you may see strange behavior.
You could have these functions take a pointer to struct (a Title *
), and pass the address of t
to both functions. I didn't fully examine the code so this may not be a comprehensive assessment of the issues in the code.
Upvotes: 1