Hey guys. I just completed an assignment that had me using arrays to decipher some code. I completed this assignment successfully and got the correct answer, but I could not follow the instructor's guidelines fully because of a small error which occurred. The error has to do with reading in from a file.
I have created a file named cquote.txt which contains one line. The line is "TO C OR NOT TO C - THAT IS THE QUESTION!". My goal is to read this line in from file and store it in an array. To accomplish this, I used the fgets() function as seen in my example below.
Code:
#include <stdio.h>
FILE *cquote;
main()
{
char code[41];
int i;
fopen_s(&cquote, "cquote.txt", "r");
while (!feof(cquote))
fgets(code, sizeof(code), cquote);
fclose(cquote);
for (i = 0; i < 41; i++)
{
printf("%c", code[i]);
}
getchar();
}
With this code I get my desired output, namely "TO C OR NOT TO C - THAT IS THE QUESTION".
However, part of the assignment was to use a function to get the input. So now I modify my code and produce this.
Code:
#include <stdio.h>
FILE *cquote;
void getLine(char code[]);
main()
{
char code[41];
int i;
getLine(code);
for (i = 0; i < 41; i++)
{
printf("%c", code[i]);
}
getchar();
}
void getLine(char code[])
{
fopen_s(&cquote, "cquote.txt", "r");
while (!feof(cquote))
fgets(code, sizeof(code), cquote);
fclose(cquote);
}
However when I execute this code, I do not get the line from the file returned, instead I get a bunch of nonsensical characters. What did I do wrong here? I'm guessing the problem is related to pointers, but I can't figure out what exactly. Anyway, the assignment was turned in with the code placed in the main body, and not in a function. However I would appreciate any input as to why the function did not work correctly.
Thank you.