Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

I am trying to read in a string from a file and set one of the members of my str

ID: 3626158 • Letter: I

Question

I am trying to read in a string from a file and set one of the members of my struct to that string. A last name for example. the error that i get in DevC++ says that I have incompatible types in assignment. I dont know much about structs so any help would be appreciated. I was basically practicing in this code so just pay attentions to the parts about the struct member assignment. Thanks


#include <stdio.h>

typedef struct Knights
{
char firstName[20];
char *lastName[20];
int numbers[6];
} KB;

int main(void)
{
struct KnightsBallLottoPlayer example;
FILE *infile;
FILE *outfile;

int number;
char string[20];
char string2[20];

infile = fopen("input.txt", "r");
outfile = fopen("out.txt", "w");

fscanf(infile, "%d", &number); // reads in first number in text file
fscanf(infile, "%s", &string); // reads in first string in file
fscanf(infile, "%s", &string2); // reads in second string in file

printf("%d, %d, %s, %s", number, number, string, string2);
example.lastName = string; //trying to assign here and print
printf("%s", example.lastName);

fclose(infile);
fclose(outfile);

system("PAUSE");
return 0;



}

Explanation / Answer

Hey all pretty good, just a few errors which the changed lines are in red. In DeC++ it does not recognize system("pause"); So i dont know what your doing for that line, i just removed it and tested the program while debugging it. Anyways here ya go

#include



typedef struct Knights
{
char firstName[20];
char *lastName; //you cant this with the [20] as this is no longer a dynamic array.
int numbers[6];
} KB;

int main(void)
{
struct Knights example;
FILE *infile;
FILE *outfile;

int number;
char string[20];
char string2[20];

infile = fopen("input.txt", "r");
outfile = fopen("out.txt", "w");

fscanf(infile, "%d", &number); // reads in first number in text file
fscanf(infile, "%s", &string); // reads in first string in file
fscanf(infile, "%s", &string2); // reads in second string in file

printf("%d, %d, %s, %s", number, number, string, string2);

example.lastName=malloc(sizeof(string));//Must allocate the space for any dynamic array in C
example.lastName = string; //trying to assign here and print
printf("%s", example.lastName);

fclose(infile);
fclose(outfile);

//NO system("pause")
return 0;
}

So these are all the problems that i could find.

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote