[英]C program load string into array within a function
so i have this simple program where i have to load values into arrays in another function, have csv file with some data of people randomly generated, separated by ;所以我有这个简单的程序,我必须在另一个函数中将值加载到数组中,有一个 csv 文件,其中包含一些随机生成的人的数据,由 ; 分隔; and need to load into 3 separate arrays
并且需要加载到 3 个单独的数组中
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
//not all necessary just the usual i put at the beggining
int main()
{
char name[100];
char surname[100];
int birth[100];
load_values(name,surname,birth);
}
int load_values(name,surname,birth)
FILE *data;
data = fopen("list_of_values.csv","r");
char letter;
while(letter = getc(data)) != EOF){ //using this to go trough the file, yes it is quite bad also need help :D
fgets(data,"%s","%s","d",&name,&surname,&birth) ///reads the file by lines and puts walues into arrays?
return (name,surname,birth);
}
list_of_values.csv look like this
Tom Brombadil;1997
Joh-Bob Larson;1999
Evan Thompson;1899
//probably the ; will be a problem too :/
expecter result is for the arrays to hold values like:预期结果是让数组保存如下值:
name[Tom,Joh-Bob,Evan]
surname[Brombadil,Larson,Thompson]
birth[1997,1999,1899]
It seems that you are stuck at this point:似乎你被困在了这一点上:
while(letter = getc(data)) != EOF){ //using this to go trough the file, yes it is quite bad also need help :D
fgets(data,"%s","%s","d",&name,&surname,&birth) ///reads the file by lines and puts walues into arrays?
getc
and fgets
work in different ways: getc
和fgets
以不同的方式工作:
getc
consumes a byte getc
消耗一个字节
fgets
consumes a buffer of n bytes fgets
消耗 n 字节的缓冲区
Don't mix them, to scan a line from the csv you want something like:不要混合它们,从你想要的 csv 扫描一行:
char buf[1024];
while (fgets(buf, sizeof buf, data))
{
if (sscanf(buf,"%99s,%99s,%d", name, surname, &birth) != 3)
{
fprintf(stderr, "Wrong format. Expected = <string> <string> <int>\n");
exit(EXIT_FAILURE):
}
}
Notice that %99s
is useful to avoid buffer overflows.请注意,
%99s
可用于避免缓冲区溢出。
But as pointed out by @SteveSummit in a comment, you have space for only one line in the strings:但正如@SteveSummit 在评论中指出的那样,字符串中只有一行:
char name[100]; // Space for 1 line
char surname[100]; // Space for 1 line
int birth[100]; // Space for 100 lines
If you want to store an array of lines you need another structure, ie a linked list or a dynamic allocated array using realloc
.如果要存储行数组,则需要另一种结构,即使用
realloc
链表或动态分配的数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.