输入后的程序块
Program blocks after input
此代码在 scanf()
之后立即阻塞:
int main(int argc, char *argv[]) {
puts("Algorithms test kit");
long input_size;
FILE *output=fopen("output.txt","w+");
do {
printf("Enter sample size(0 goes on to next test) > ");
scanf (" %li ",&input_size);
printf ("#");
if (input_size==0) break;
int64_t *data=sorting_prepare_data(input_size);
int64_t *bsort_copy=calloc(input_size,8);
int64_t *qsort_copy=calloc(input_size,8);
memcpy(bsort_copy,data,input_size*8);
bubblesort(bsort_copy,input_size);
memcpy(qsort_copy,data,input_size*8);
quicksort(qsort_copy,input_size);
for (size_t i=0;i<input_size;i++) {
fprintf(output,"%lld\t%lld\t%lld\n",data[i],bsort_copy[i],qsort_copy[i]);
printf(".");
}
free(data); free(bsort_copy); free(qsort_copy);
} while (input_size);
return;
}
其中 bubblesort()
和 quicksort()
是各自算法的手写实现,sorting_prepare_data()
是在数组上调用自定义 PRNG 的辅助函数。阻塞的可能原因是什么?该程序已使用GCC编译,没有出现错误。
我试过你的代码并设法重现了奇怪的行为。如果你删除 "%li"
周围的 " "
它就不会再阻塞了。
问题是空白 space,因为 scanf
期望输入也与空 space 匹配。
来自 scanf
文档:
All
conversions are introduced by the % (percent sign) character. The format string may also contain other characters. White space (such as
blanks, tabs, or newlines) in the format string match any amount of
white space, including none, in the input. Everything else matches
only itself. Scanning stops when an input character does not match
such a format character. Scanning also stops when an input conversion
cannot be made.
此代码在 scanf()
之后立即阻塞:
int main(int argc, char *argv[]) {
puts("Algorithms test kit");
long input_size;
FILE *output=fopen("output.txt","w+");
do {
printf("Enter sample size(0 goes on to next test) > ");
scanf (" %li ",&input_size);
printf ("#");
if (input_size==0) break;
int64_t *data=sorting_prepare_data(input_size);
int64_t *bsort_copy=calloc(input_size,8);
int64_t *qsort_copy=calloc(input_size,8);
memcpy(bsort_copy,data,input_size*8);
bubblesort(bsort_copy,input_size);
memcpy(qsort_copy,data,input_size*8);
quicksort(qsort_copy,input_size);
for (size_t i=0;i<input_size;i++) {
fprintf(output,"%lld\t%lld\t%lld\n",data[i],bsort_copy[i],qsort_copy[i]);
printf(".");
}
free(data); free(bsort_copy); free(qsort_copy);
} while (input_size);
return;
}
其中 bubblesort()
和 quicksort()
是各自算法的手写实现,sorting_prepare_data()
是在数组上调用自定义 PRNG 的辅助函数。阻塞的可能原因是什么?该程序已使用GCC编译,没有出现错误。
我试过你的代码并设法重现了奇怪的行为。如果你删除 "%li"
周围的 " "
它就不会再阻塞了。
问题是空白 space,因为 scanf
期望输入也与空 space 匹配。
来自 scanf
文档:
All conversions are introduced by the % (percent sign) character. The format string may also contain other characters. White space (such as blanks, tabs, or newlines) in the format string match any amount of white space, including none, in the input. Everything else matches only itself. Scanning stops when an input character does not match such a format character. Scanning also stops when an input conversion cannot be made.