c - 在C中将一个单词(char [])插入一个结构单词(char [])中

标签 c struct text-files scanf

所以我正在从包含许多不唯一单词的文本文件中读取每个单词。我应该找到唯一单词的数量并将这些单词存储到一个名为 word 的结构变量中

我的主要问题在“我的问题在下面”的注释下标出

结构代码:

  typedef struct {
  char word[101];
  int  freq;

  } WordArray;

代码:

  //temp[i].word is a temporary structure that scans ALL words
  //input[i].word is the structure with unique words

  word = fscanf(finput, "%s", &temp[i].word);

 //if the word in temp[i] is in input[j].word then it is not unique
 // so frequency of word is incremented

   for(j = 0; j < 200; j++) { 
     if(strcmp(temp[i].word,input[j].word) == 0){
        contains = 1;
        input[j].freq++;
     }
  }

     // MY PROBLEM IS HERE BELOW
    if(contains != 1) { // since contains is not 1 then it is unique

     input[i].word = temp[i].word // i want to put this word in input[i].word but this
                                  // produces incompatible type error
                                  // i tried strcpy and strncpy no luck...
     input[i].freq++;
     uniqueWords++;
  }

最佳答案

删除&

fscanf(finput, "%s", &temp[i].word);

改成

fscanf(finput, "%s", temp[i].word);

或者取第一个元素的地址,相当于上一行

fscanf(finput, "%s", &temp[i].word[0]);

传递的数组衰减为指向数组第一个元素的指针,所以它们是等价的

fscanf(finput, "%s", temp[i].word); /* passed a pointer to the first elemn */
fscanf(finput, "%s", &temp[i].word[0]); /* passed the address of the first element */

另外,为fscanf添加一个限制以防止像这样的缓冲区溢出

fscanf(finput, "%100s", temp[i].word); /* passed a pointer to the first elemn */

其中数字应比数组大小少 1

你不能在这行给数组赋值

input[i].word = temp[i].word

是错误的,你应该使用strcpy

strcpy(input[i].word, temp[i].word);

关于c - 在C中将一个单词(char [])插入一个结构单词(char [])中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27846566/

相关文章:

c - 将 char 数组从指针复制到行文件后的奇怪输出

c++ - C/C++ 结构内存布局等效

c++ - 类中未识别公共(public)结构?

C# - 使用正则表达式将数据排序到/从列表框

C# 如何将文本文件中的几组单词放入数组中

python - 在没有单引号Python的情况下将数字文本文件读入列表

c - 简单的C程序。从函数返回的字符串导致错误

c - printf 的意外输出

c - 测量使用 Clang/LLVM 生成的函数的大小?

c++ - 避免在 C++ 中使用结构填充