从文件中读取并将值放入结构数组时出现问题
Trouble reading from a file and putting values into an array of structs
问题:我在从.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 %dn", 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.
相关文章:
- 从函数中全局删除并重新实例化数组结构,而无需在编译时知道数组的大小
- 如何使用函数的输出初始化 const 数组结构字段?
- 传递数组结构、ofstream 和 interger 以运行
- 从文本文件中读取并输入到数组结构中,然后显示读取的数据C++
- 将文本文件读取到数组结构中
- C/C++中数组结构和数组结构的通用接口
- C++ MDC final-在字符类型的数组结构中按字母顺序对记录中的名称进行排序
- C++ 使用数组结构创建平衡的二叉搜索树
- C++:释放动态数组(结构成员)和指向此结构的指针的方法
- 使用 vector 在 c++ 中声明 3D 数组结构
- 数组结构无法正确打印
- 如何在C++中访问数组结构内部的数组结构
- CIN进入数组结构似乎什么也没输入
- ifstream将数组结构到txt文件中,然后尽可能将其提取为数组
- wlanapi-将WlanFreeMemory释放其WLAN_INTERFACE_INFO数组结构
- 显示数组结构 c++
- C++ 使用函数访问数组结构的方法是什么?
- 将庞大的数组结构复制到 GPU
- 如何封送包含字符矩阵的数组结构
- C++多维数组结构的对齐