gpt4 book ai didi

C读取文件内容到字符串数组中

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

我需要将文件的内容加载到两个字符串数组中。我尝试了以下方法,但它不起作用。file.txt 包含 10 条记录,每条记录有两个以空格分隔的字符串值。

代码:

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

int main(void) {
char line[12][20];
FILE *fptr = NULL;
int i = 0;
int tot = 0;

fptr = fopen("file.txt", "r");
char arr[20][20];

while (fgets(line, sizeof(line), fptr)) {
strcpy(arr[i],line);
i++;
}
tot=i;
for (int i=0; i<tot; i++) {
printf("first value %s",arr[i][0]);
printf("second value is %s",arr[i][1]);
printf("\n");
}
return 0;
}

最佳答案

如果我理解正确,您正在尝试将数据存储在如下结构中:

{{"line1A", "line1B"}, {"line2A", "line2B"}, {"line3A", "line3B"}}

看起来您需要一个数组,其中每个元素由两个数组(字符串)组成,一个用于每行的第一个值,一个用于第二个值。如果是这种情况,您需要一个三维字符数组。

在下面的示例中,我将 arrayOfLines 声明为包含 12 个元素的数组,每个元素都有 2 个字符数组(每行两个值),每个字符串中有 20 个字符的空间( NULL 终止的字符数组)

您的代码还存在一些其他问题:

  • fgets() 的第一个参数应该是 char * - 指向字符串缓冲区的指针。您的代码传入一个多维字符数组。
  • 您的 while 循环应继续,直到 fgets 返回 NULL
  • 您需要将每一行拆分为多个字符串
  • 使用 strcpy() 复制字符串时检查缓冲区是否溢出

在示例代码中,我使用了由 "" 空格字符分隔的 strtok() - 您可能需要尝试一下 - strtok 可以接受字符数组用作分隔符。在示例中,我使用第一个空格字符分割第一个字符串,第二个字符串由行尾分隔。

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


int main(void)
{
// Array for 12 lines, each with 2 strings, each string max 20 chars
// Adjust values as required.
char arrayOfLines[12][2][20];

FILE *fptr = NULL;
int i = 0;
int tot = 0;
fptr = fopen("file.txt", "r");
// char arr[20][20]; not needed

char line[20];
while(fgets(line, sizeof(line) / sizeof(line[0]), fptr) != NULL)
{
// Rudimentary error checking - if the string has no newline
// there wasn't enough space in line
if (strchr(line, '\n') == NULL) {
printf("Line too long...");
return EXIT_FAILURE;
}
// Split string into tokens
// NB: Check for buffer overruns when copying strings
char *ptr1 = strtok(line, " ");
strcpy(arrayOfLines[i][0], ptr1);
char *ptr2 = strtok(NULL, "\n");
strcpy(arrayOfLines[i][1], ptr2);
i++;
}

tot=i; // Unecessary - just use a different variable in your loop and use i as the upper bound

for (int i=0;i<tot;i++)
{
printf("first value %s\n", arrayOfLines[i][0]);
printf("second value is %s\n", arrayOfLines[i][1]);
printf("\n");
}

return 0;
}

关于C读取文件内容到字符串数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58716823/

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