c - 尝试 scanf 但无法访问它的值,除非输入另一个值
问题描述
我正在尝试动态初始化一个数组,但是当我while
第一次进入循环时printf
打印语句,但是printf
除非我输入另一个值,否则下一个语句不会执行。我想把值放在
0--->n-1
第一次printf
执行语句,但第二次不执行,除非我输入任何值。尝试输入 5 作为尺寸,并输入 0,1,2,3,4 作为值。
#include <stdio.h>
#include <malloc.h>
void main() {
Ex5();
system("pause");
}
void Ex5()
{
int size_a,n_res=0,res=0;
int *arr_a = input_array_dyn(&size_a);
res = includes(arr_a, size_a);
printf("res is %d ", res);
free(arr_a);
}
int* input_array_dyn(int *size) {
int i=0, *p_to_arr;
printf("enter size of arr:");
scanf_s("%d", size);
p_to_arr = (int*)calloc(*size,sizeof(int));
while(i<*size) {
printf("enter %d element", i);
scanf_s(" %d ", &p_to_arr[i]);
i++;
}
return p_to_arr;
}
解决方案
格式字符串在
scanf_s(" %d ", &p_to_arr[i]);
很麻烦,可能是您的问题的原因。
格式字符串的问题是尾随空格。尾随空格意味着scanf_s
将读取所有尾随空格字符,直到没有更多空格为止。问题是scanf_s
要知道没有更多的空格,您必须输入一些非空格输入。
这会导致scanf_s
阻塞,直到您编写第二个输入。
解决方案是在格式字符串中根本没有任何空格:
scanf_s("%d", &p_to_arr[i]);
也不需要前导空格,因为说明"%d"
符会自动跳过前导空格。
推荐阅读
- c++ - struct int 数据类型不适用于关系运算符
- sql-server - 安装后无法连接到 SQL Server 2019 上的 localhost
- c - 有界树遍历的 C 算法
- c++ - C++ 是否优化了变量的副本?
- kdb - KDB - 从表中引用函数
- unity3d - 无法在 Unity 中更改边缘对撞机的点
- r - 如何将名称不为 NULL 的列表传递给 r 中的 do.call 的参数
- javascript - 在 NodeJS/Express 中访问本地存储的文件
- python - 将大约 20 个表从 BigQuery 传输到 MongoDB 时出现“chunkedEncodingError,连接断开:OSError 104”(通过 Python)
- python-3.x - 0 升级,0 新安装,0 删除,1 未升级。不升级(ubuntu 20.04)