简体   繁体   English

fscanf不将字符串读入数组

[英]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. words[i]是指向随机存储器位置的指针。 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. 将分配一个缓冲区来保存n个指向char的指针, words只是指向指针数组的指针。 You need allocate enough memory for words[i] (the pointer to ) to hold the string: 您需要为words[i] (指向的指针)分配足够的内存以容纳字符串:

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: (可选)您可以使用GNU的 getline 扩展 (如果使用gcc)来执行所需的操作:

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. 实际上,此功能没有魔术,它只是在后台进行内存分配以保存您的内存,而您有责任释放它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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