Elliot Gorokhovsky
Elliot Gorokhovsky

Reputation: 3772

fscanf not reading strings into array

Why doesn't this main print anything? It should print the first word in the file.

int main(int argc, char *argv[])
{
  FILE *file = fopen(argv[1], "r");
  int n = atoi(argv[2]);

  char **words = new char*[n];
  for(int i = 0; i < n; i++)
    {
      fscanf(file, "%s ", words[i]);
    }
  cout << words[0] << endl;
}

Upvotes: 0

Views: 385

Answers (2)

jfly
jfly

Reputation: 8020

char **words = new char*[n]; will allocate a buffer to hold n pointers to char, words is just a pointer to an array of pointers. You need allocate enough memory for words[i](the pointer to ) to hold the string:

for (i=0; i < n; ++i ) {
    words[i] = new char[your_max_string_len];
}

Optionally you can use getline extension of GNU(if you use gcc) to do what you want:

size_t len = 0;
ssize_t read;
read = getline(&words[i], &len, stdin);
...
free(words[i]);

Actually, there is no magic in this function, it just does the memory allocation under the hood to save yours, and it's your responsibility to free it.

Upvotes: 2

F&#225;bio Junqueira
F&#225;bio Junqueira

Reputation: 2781

words[i] is a pointer that points to a random memory location. Make sure to make it point to allocated memory.

//Now words[i] points to the 1000 bytes allocated with the new keyword
words[i] = new char[1000];
//fscan will write the input to those bytes
fscanf(file, "%s ", words[i]);

Upvotes: 2

Related Questions