I am trying to scan unsigned integers until EOF
(Ctrl-D on my platform). The integers scanned should be only positive and since 0
is considered unsigned I need to check if 0
was entered.
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);
My goal is that the user will type the integers until pressed Ctrl-D and all of the unsigned integers will be saved on the list1
pointer. But instead this happens:
Enter positive integers to the first list:23 10
Error - you must enter positive numbers
For some reason, the code only stops when I press Ctrl-D twice and it registers a number as 0
.
CodePudding user response:
scanf("%u", list1 cnt1)
returns:
1
if the conversion was successful0
if the pending input cannot be converted to a numberEOF
if the stream is at end of file.
Hence you should write:
while (scanf("%u", list1 cnt1) == 1) {
Furthermore, it would be preferable to only reallocate the array if the number needs to be appended:
#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;
}