简体   繁体   中英

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;
}

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]);

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM