c - for 循环没有考虑执行的最后一个循环
问题描述
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main()
{
int count;
scanf("%d",&count);
char **array;
array = (char **) malloc(sizeof(char* ) * count);
for(int i=0;i<count;i++)
{
*(array +i) = (char *)malloc(sizeof(char) * 1000);
}
for(int i=0;i<count;i++)
{
fgets(*(array + i) , 1000 , stdin);
}
for(int i=0;i<count;i++)
{
printf("%s:::",*(array+i));
}
printf("\n");
return 0;
}
我正在尝试创建一个包含计数元素的字符串数组。我使用 fgets 函数使用 for 循环将元素读入数组。但是当我尝试打印元素时,std 输出中缺少最后一个元素。我尝试使用 count =8;
- 1
- 2
- 309876567
- 67564746
- 111
- 20043
- 75647
- 200
这些是我的投入。但是200不会被打印出来..
解决方案
试试这个版本,评论中解决的问题。
int main(void) {
int row, col /* 1000 */;
scanf("%d%d",&row, &col);
getchar();/* to clear stdin buffer */
char **array = malloc(sizeof(char*) * row);
for(int i=0;i < row; i++) {
/* allocate memory */
*(array +i) = malloc(sizeof(char) * col);
/* scan the data */
fgets(*(array + i), col, stdin); /* fgets add \n at the end of buffer if read */
array[i][strcspn(array[i], "\n")] = 0; /* remove trailing \n */
/* print it */
printf("%s\n",*(array+i));
}
printf("\n");
/* free dynamically allocated memory @TODO */
return 0;
}
推荐阅读
- r - 尝试从具有特定条件的数据框中获取某些行
- r - Kable cell_spec 格式删除表格的行标签
- r - R 中的 xgboost:xgb.cv 的 early_stopping_rounds 的容差是多少?
- javascript - 仅使用提交按钮以 HTML 表单执行 onsubmit 功能
- mysql - sql 只返回具有特定列值的行
- yaml - 指定长名称空间和动态参数
- javascript - fullcalendar v5 getEventByID 不是函数
- sql - 两个字段上的 SQL 日期过滤器
- python - 使用python从谷歌驱动器下载文件
- android - android中的LayoutTransition / Animation仅在Infinite while循环中工作