首页 > 解决方案 > 尝试 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;
}

标签: cscanf

解决方案


格式字符串在

scanf_s(" %d ", &p_to_arr[i]);

很麻烦,可能是您的问题的原因。

格式字符串的问题是尾随空格。尾随空格意味着scanf_s将读取所有尾随空格字符,直到没有更多空格为止。问题是scanf_s要知道没有更多的空格,您必须输入一些非空格输入。

这会导致scanf_s阻塞,直到您编写第二个输入。

解决方案是在格式字符串中根本没有任何空格:

scanf_s("%d", &p_to_arr[i]);

也不需要前导空格,因为说明"%d"符会自动跳过前导空格。


推荐阅读