-2

I just startet learning C and I am stuck with printing the elements of an array. I want to read a .txt-file and save it to an array. Then print the elements of the array.

The text file says:

1
2
3
4

My C code says:

#include <stdlib.h>
#include <stdio.h>

int main() {

FILE *fp;
char myArray[30];
int wordCount = 0, i;


fp = fopen("list.txt", "r");

if(fp != NULL) {
    while(!feof(fp)) {
        fscanf(fp, "%s", &myArray[wordCount]);
        wordCount++;}
    }

printf("%s\n", myArray);
printf("%s\n", &myArray[1]);      // intend to print 2nd element
printf("%d\n", arrayOfWords[1]);  // intend to print 2nd element

return 0;
}

The output says:

1234
234
50

Neither &myArray[1] nor myArray[1] works.

BeldCode
  • 67
  • 1
  • 7
  • 1
    printf("%c\n", myArray[1]) – CraftyMonkey Apr 01 '19 at 20:05
  • 2
    Since you aren't checking the return value of fscanf, you increment wordcount regardless of whether or not you actually read a word. Always check return values. – stark Apr 01 '19 at 20:07
  • 1
    Useful reading about one bug in your code: https://stackoverflow.com/questions/5431941/why-is-while-feoffile-always-wrong – Shawn Apr 01 '19 at 20:16
  • And do you really want to use different offsets into the same char array for all the strings you read? That's not going to work at all when it comes to printing them and will give you buffer overflows real fast... – Shawn Apr 01 '19 at 20:18
  • Do you want to save a sequence of *strings* (0-terminated sequences of characters) in a 1D array of `char`, such that `myArray` will look like `{'1', 0, '2', 0, '3', 0, '4', 0}`? Or do you want `myArray` to look like `{'1', '2', '3', '4'}`? – John Bode Apr 01 '19 at 20:22
  • myArray is supposed to look like `{'1', '2', '3', '4'}` – BeldCode Apr 01 '19 at 20:47
  • 1
    @BeldCode: In that case, use `" %c"` as your format string as opposed to `"%s"` (note the blank space before the `%`, that's necessary to skip over any whitespace). Also, `while (!feof(fp))` won't work the way you expect - the better way to do this is `while ( fscanf( fp, " %c", &myArray[wordcount] ) == 1 ) wordcount++;` – John Bode Apr 03 '19 at 20:21

1 Answers1

0

The problems here, myArray[] is not a array of strings, it only one string... You can fix this problem by defining myArray like this

   //30 string array each holding 30 characters.
   char myArray[30][30]