gpt4 book ai didi

c - 如何将名称文件读入数组

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

我需要帮助读取名称列表并将它们存储到字符串中。我已经为字符串分配了内存,我只需要帮助实际读取它们并将它们存储在其中。这是我已经编写的信息和代码。我只需要 insert_data 函数的帮助。

#include <string.h> 
#include <stdio.h>
#include <stdlib.h>

#define MAX_STRING_LEN 25

void insert_data(char **strings, const char *filename, int size);
void allocate(char ***strings, int size);

int main(int argc, char* argv[]){

if(argc != 4){
printf("Wrong number of args");
}

char **pointer;
int size = atoi(argv[1]);
allocate(&pointer, size);
insert_data(pointer, argv[2], size);
}



void allocate(char ***strings, int size){

int i;
*strings = (char**) malloc(sizeof(char**) * size);

for( i = 0; i < size; i++)
{
(*strings)[i] = malloc(sizeof(char) * MAX_STRING_LEN);
}
}

这是我需要帮助的功能:

void insert_data(char **strings, const char *filename, int size){

FILE *input;
input = fopen(filename, "r");

int i;
for (i = 0; i < size; i++){

fscanf(input,"%s", (*strings)[i]);

}

fclose(input);
}

这是我正在阅读的列表:

matt 
susan
mark
david
aden
phil
erik
john
caden
mycah

最佳答案

#include <string.h> 
#include <stdio.h>
#include <stdlib.h>

#define MAX_STRING_LEN 25
#define _S(x) #x
#define S(x) _S(x)

void insert_data(char **strings, const char *filename, int size);
void allocate(char ***strings, int size);

int main(int argc, char* argv[]){

if(argc != 3){
printf("Wrong number of args\n");
printf("Usage:%s size filename\n", argv[0] ? argv[0] : "prog");
exit(-1);
}

char **pointer;
int size = atoi(argv[1]);
allocate(&pointer, size);
insert_data(pointer, argv[2], size);
int i;
for(i=0;i<size;++i){
printf("%s\n", pointer[i]);
free(pointer[i]);
}
free(pointer);
return 0;
}

void allocate(char ***strings, int size){
int i;

*strings = malloc(sizeof(char*) * size);
for( i = 0; i < size; i++) {
(*strings)[i] = malloc(sizeof(char) * (MAX_STRING_LEN+1));
}
}

void insert_data(char **strings, const char *filename, int size){
FILE *input= fopen(filename, "r");
int i;
for (i = 0; i < size; i++){
fscanf(input,"%" S(MAX_STRING_LEN) "s", strings[i]);
}
fclose(input);
}

关于c - 如何将名称文件读入数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24320058/

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