0

Ive been trying to read from an input text file using strings but every time I run my code it reads null or does not read from file at all. I am using xcode so Ive been putting the path instead of the file name. I dont know what I am doing wrong can somebody please help?

char jumbled[SIZE] = "", solution[SIZE] = "";
//declare character and file pointer
FILE* inPtr;
//greet the user and disply the instructions
GameInstructions();
//connect to the input file
inPtr = fopen("filename.txt", "r");
do {
    printf("\nReady to play a round of Jumbled!\n");
    //read 2 words fromthe file
  fscanf(inPtr, " %s", &jumbled[0]);
  fscanf(inPtr, " %s", &solution[0]);
    //print the words to make sure they were read from the file correctly
    printf("\n jumbled is %s and the solution is %s\n", &jumbled[0], &solution[0]);
pmg
  • 106,608
  • 13
  • 126
  • 198
  • 1
    You don't need `&` or `[0]` for your scanfs and prints... `scanf("%s", jumbled);` and `printf("%s", jumbled);` are good enough. – pmg Nov 24 '21 at 15:03
  • Did you verify that the function `fopen` succeeded, i.e. that it is not returning `NULL`? You don't seem to be checking the return value in your code. – Andreas Wenzel Nov 24 '21 at 15:05
  • 1
    After `fopen()` check that you have a valid file pointer: `if (inPtr == NULL) { perror("filename.txt"); exit(EXIT_FAILURE); }` – pmg Nov 24 '21 at 15:06
  • @pmg when I remove the & and [0] it does not read from file – Michelle Nov 24 '21 at 15:10
  • @AndreasWenzel how can I check if it succeeded? I made sure that it was a plain text file and I used the path – Michelle Nov 24 '21 at 15:11
  • `&jumbled[0]` and `jumbled` are 100% equivalent in the situations above. Your problem is not with the `&` and `[0]`. – pmg Nov 24 '21 at 15:11
  • What is `SIZE` defined as? – pmg Nov 24 '21 at 15:14
  • The first comment by @pmg was not intended as a solution to your problem, but rather as a side-note. When you write the expression `jumbled`, the array automatically [decays](https://stackoverflow.com/q/1461432/12149471) to a pointer to the first element, i.e. to `&jumbled[0]`, so there is no need for you to explicitly write it. – Andreas Wenzel Nov 24 '21 at 15:14
  • 1
    @MichelleVieira: Your question on how to to check the return value of `fopen` has already been answered by someone else, in the third comment. – Andreas Wenzel Nov 24 '21 at 15:18
  • Oh i see Thank you and SIZE is 30 – Michelle Nov 24 '21 at 15:19

0 Answers0