gpt4 book ai didi

c++ - 从文件读取并将值放入结构数组时遇到问题

转载 作者:行者123 更新时间:2023-11-30 21:30:02 25 4
gpt4 key购买 nike

问题:我在从 .csv 文件获取输入并将其粘贴到结构数组中时遇到问题。我的问题是编译器不允许我从 char 变量 word 中分配 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com