我有以下代码:
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.我似乎无法弄清楚什么是错误的。
答案 0 :(得分:0)
问题出在
行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]);
它会正确打印输出...
答案 1 :(得分:0)
要在行尾删除CR或LF,请尝试:
char *cp;
while((cp=strchr(words[i], '\r')))
*cp='\0';
while((cp=strchr(words[i], '\n'))(
*cp='\0';
而不是:
for(j = strlen(words[i]) - 1; j >= 0 && (words[i][j] == '\n' || words[i][j] == '\r'); j--)
;
words[i][j] = '\0';