gpt4 book ai didi

c - 将文本行存储在数组中,C

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

我是 C 语言新手,我很困惑如何读取文件并将每一行存储到数组的索引中。

示例文件:

What color is the sky?
Red
Orange
Yellow
Blue

期望的代码结果:

input[0] = What color is the sky?
input[1] = Red
input[2] = Orange
input[3] = Yellow
input[4] = Blue

这是我到目前为止所拥有的:

char input[60];

//declare string array of size 80, for 80 lines

for(int i = 0; fgets(input, sizeof(input), inFile)!=NULL; i++){

//string[i] = input; storing this line to the string index

}

//later on use the string[80] that now has all lines

我明白声明input[60]只确定每行的长度,而不确定行数。我已经习惯于思考其他编码语言中的字符串,以至于 char 的使用让我感到厌烦。我尝试过视频教程,但它们对我没有帮助。

最佳答案

文件的每一行都是一个不同的字符串,每个字符串都是一个指向数组的char*指针;所以你需要的是一个 char* 指针的一维数组(或者一个 char 的二维数组。)

char *line[ MAX_LINES ];  // 1D array of char* pointers.

您可以初始化二维 char 数组,也可以为每行 1D char* 指针分配内存。

这是 malloc 方法的示例。它存储的变量称为“行”而不是“输入”;但如果您愿意,您可以交换变量名称,并更改打印格式来解决您的特定问题。这只是作为将字符串读入内存的示例,就像您希望的那样。实际系统中没有少于 4K 的堆空间,因此我省略了 malloc 内存检查。

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

#define MAX_LINES 10
#define MAX_LEN 60

int main( int narg, char *arg[] ) {
char input[ MAX_LEN ];
char *line[ MAX_LINES ];
FILE *inFile;
int i,j;

if ( narg != 2 ){fprintf( stderr, "Use: %s filename\n", arg[0] ); return 2;}
if (!(inFile=fopen(arg[1],"r") )){
fprintf( stderr, "Can't open '%s'\n",arg[1]);
return 2;
}

for ( i=0; i<MAX_LINES && fgets(input, sizeof(input), inFile ); ++i ) {
int lineLen=strlen(input) + 1;
line[i] = strncpy( malloc( lineLen ), input, lineLen );
}

for ( j=0; j<i; ++j ) { printf( "Line %d:%s", j+1, line[j] ); free(line[j]); }
fclose(inFile);
return 0;
}

关于c - 将文本行存储在数组中,C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52398698/

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