问题:我无法从.csv文件中获取输入并将其粘贴到结构数组中。我的问题是,编译器不允许我从char可变字分配G.word。我不知道为什么不这样做,因为我的结构和初始占位符变量都属于同一类型。谢谢。它必须在C中,但是赋值使我们可以使用C ++函数来处理文件。除此之外,我坚持使用C。

/*Sample of the data being read.
airport 2007    175702  32788
airport 2008    173294  31271
request 2005    646179  81592
request 2006    677820  86967
request 2007    697645  92342
request 2008    795265  125775
*/

struct NGram{
char *nword;
int year;
int wordCount;
int uText;
};

char fileName[]="very_short.csv";

int main() {
char word[81];
int year;
int wordCount;
int uniqueTextCount;
int i = 0;
int j = 0;

int size = 100000; //initialize array at 100000
struct NGram G[size];

FILE *inFile;    // declare file pointer
inFile = fopen( fileName,"r");

while( fscanf( inFile, "%s %d %d %d", word, &year, &wordCount, &uniqueTextCount) != EOF) {
    //printf("%s %d %d %d\n", word, year, wordCount, uniqueTextCount);

        if (year > 1800 && year < 2000) { //store values in struct only if between these dates
        G[j].nword = word;
        G[j].year = year;
        G[j].wordCount = wordCount;
        G[j].uText = uniqueTextCount;
            j++;
        }

}
return 0;
}

最佳答案

将数组复制到指针的方法错误。需要分配内存,然后使用memcpy()复制。

// char *nword;
// char word[81];
// G[j].nword = word;

size_t wsize = strlen(word) + 1;
G[j].nword = (char *) malloc(wsize);  // drop cast if compiling in C, could add NULL check
memcpy(G[j].nword, word, wsize);


读取行定向文件的一种简单的C方法是读取1行,然后对其进行解析。使用fgets()而不是fscanf()。使用"%n"记录扫描停止的位置。

// Zero fill G.  Not truly needed but simplifies debugging.
struct NGram G[size] = { 0 };

char buf[200];
size_t j = 0;
while (fgets(buf, sizeof buf,  inFile) != NULL) {
  if (j >= size) break;  // Too many
  char word[81];
  NGram Nbuf;
  int n = 0;
  sscanf(buf, "%80s %d %d %d %n", word, &Nbuf.year, &Nbuf.wordCount, &Nbuf.uText, &n);
  // If all fields were not scanned or something left at the end ...
  if (n == 0 || buf[n]) {
    puts("Bad Input");
    break;
  }
  if (Nbuf.year > 1800 && Nbuf.year < 2000) {
    size_t wsize = strlen(word) + 1;
    Nbuf.nword = (char *) malloc(wsize);  // drop cast if compiling in C
    memcpy(Nbuf.nword, word, wsize);
    G[j] = Nbuf;
    j++
  }
}

// Do something with G[0] to G[j-1]

// free each ( 0 to j-1) G[].nword when done.

关于c++ - 无法读取文件并将值放入结构数组中,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28312900/

10-11 22:07
查看更多