我正在嘗試掃描無符號整數,直到EOF(Ctrl-D在我的平臺上)。掃描的整數應該只是正數,因為0被認為是無符號的,我需要檢查是否0輸入了。
int cnt1 = 0;
unsigned *list1;
list1 = malloc(sizeof(unsigned));
printf("Enter positive integers to the first list:");
while (scanf("%u", list1 cnt1)) { /* getting the first list */
if (*(list1 cnt1) == 0) { /* checks to see if the number entered is 0 */
printf("\nError - you must enter positive numbers");
exit(-1);
}
cnt1 ;
list1 = realloc(list1, (sizeof(unsigned) cnt1 * sizeof(unsigned)));
}
printf("\n");
free(list1);
我的目標是用戶在按下之前輸入整數,Ctrl-D并且所有無符號整數都將保存在list1指標上。但相反,這種情況發生了:
Enter positive integers to the first list:23 10
Error - you must enter positive numbers
出于某種原因,代碼僅在我按兩次時才會停止,Ctrl-D并將一個數字注冊為0.
uj5u.com熱心網友回復:
scanf("%u", list1 cnt1)回傳:
1如果轉換成功0如果掛起的輸入不能轉換為數字EOF如果流在檔案末尾。
因此你應該寫:
while (scanf("%u", list1 cnt1) == 1) {
此外,如果需要附加數字,最好只重新分配陣列:
#include <stdio.h>
#include <stdlib.h>
unsigned *read_list(int *countp) {
int count = 0;
unsigned *list = NULL;
unsigned *new_list;
unsigned num;
printf("Enter positive integers to the first list: ");
while (scanf("%u", &num) == 1) {
if (num == 0) { /* checks to see if the number entered is 0 */
printf("\nError - you must enter positive numbers\n");
continue;
}
new_list = realloc(list, sizeof(*list) * (count 1));
if (new_list == NULL) {
printf("\nError - cannot allocate memory\n");
free(list);
*countp = -1;
return NULL;
}
list = new_list;
list[count ] = num;
}
printf("\n");
*countp = count;
return list;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/486431.html
上一篇:了解回傳指向陣列的指標的指標函式
下一篇:獲取類的方法地址
