gpt4 book ai didi

c - 文件需要正确读入

转载 作者:行者123 更新时间:2023-11-30 17:34:07 28 4
gpt4 key购买 nike

我有以下代码:

int main(void)
{
int lines_allocated = 128;
int max_line_len = 100;
int lines_allocated2 = 128;
int max_line_len2 = 100;

/* Allocate lines of text */
char **words = (char **)malloc(sizeof(char*)*lines_allocated);
if (words == NULL)
{
fprintf(stderr, "Out of memory (1).\n");
exit(1);
}

FILE *fp = fopen("test1.txt", "r");
if (fp == NULL)
{
fprintf(stderr, "Error opening file.\n");
exit(2);
}
else
{
printf("Reading in test1.txt...\n");
}

int i;
for (i = 0; 1; i++)
{
int j;

/* Have we gone over our line allocation? */
if (i >= lines_allocated)
{
int new_size;

/* Double our allocation and re-allocate */
new_size = lines_allocated * 2;
words = (char **)realloc(words, sizeof(char*)*new_size);
if (words == NULL)
{
fprintf(stderr, "Out of memory.\n");
exit(3);
}
lines_allocated = new_size;
}
/* Allocate space for the next line */
words[i] = malloc(max_line_len);
if (words[i] == NULL)
{
fprintf(stderr, "Out of memory (3).\n");
exit(4);
}
if (fgets(words[i], max_line_len - 1, fp) == NULL)
break;

/* Get rid of CR or LF at end of line */
for (j = strlen(words[i]) - 1; j >= 0 && (words[i][j] == '\n' || words[i][j] == '\r'); j--)
;
words[i][j] = '\0';
}

int j;
for (j = 0; j < i; j++)
{
printf("%s\n", words[j]);
}
return 0;
}

我正在尝试读取文件并将每一行存储在单词数组中。我的输入文件包含:

1 345363

0 149378

0 234461

0 454578

但是,每行的最后一个数字会被截断。因此,当第一个索引应该打印出 345363 时,它会打印出 34536。我似乎无法弄清楚出了什么问题。

最佳答案

问题出在行上

for (j = strlen(words[i]) - 1; j >= 0 && (words[i][j] == '\n' || words[i][j] == '\r'); j--)

j = strlen(words[i]) - 1; 更改为 j = strlen(words[i]); 它将正确打印输出...

关于c - 文件需要正确读入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23508867/

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