【问题标题】:C program load string into array within a functionC程序将字符串加载到函数内的数组中
【发布时间】:2021-12-23 07:44:28
【问题描述】:

所以我有这个简单的程序,我必须在另一个函数中将值加载到数组中,让 csv 文件随机生成一些人的数据,用 ; 分隔并且需要加载到 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 :/

预期结果是数组保存如下值:

name[Tom,Joh-Bob,Evan]
surname[Brombadil,Larson,Thompson]
birth[1997,1999,1899]

【问题讨论】:

  • 您好,请发布Minimal Reproducible Example,最短的可编译代码,显示您尝试过的内容。发布的代码有很多错误,很难知道从哪里开始。
  • Nitpick 不是你的问题,但是:CSV 代表 comma 分隔值。所以这不是一个真正的 CSV 文件。
  • 如果您有char name[100],您可以读取一个最多包含 99 个字符的名称。如果您打算能够读取多个姓名(以及姓氏和出生日期),您将需要不同的数据结构。
  • 使用char变量保存getc的返回值是错误的;它必须是int。 (但在这里首先调用getc 是错误的,所以这并不重要。)
  • 上一个问题Read .csv file in C可能会给你一些想法。

标签: arrays c function file fgets


【解决方案1】:

看来你卡在了这一点上:

   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?

getcfgets 以不同的方式工作:

  • getc 消耗一个字节

  • fgets 消耗一个 n 字节的缓冲区

不要混合它们,从你想要的 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):
    }
}

注意%99s 有助于避免缓冲区溢出。

但正如@SteveSummit 在评论中指出的那样,字符串中只有一行空间:

char name[100];    // Space for 1 line
char surname[100]; // Space for 1 line
int birth[100];    // Space for 100 lines

如果要存储行数组,则需要另一种结构,即链表或使用realloc 的动态分配数组。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-31
    • 1970-01-01
    • 2023-01-19
    • 1970-01-01
    • 1970-01-01
    • 2015-03-09
    • 1970-01-01
    • 2017-01-31
    相关资源
    最近更新 更多