I wrote the following code:
int VALUE = 10;
int counter = 0;
char c;
while (true) {
if(scanf("%c", &c) != 1) {
return NULL;
}
if (c == '\n') {
break;
}
if (counter % VALUE < VALUE - 1) {
num[counter] = c;
counter++;
} else {
char* temp = (char*) malloc((counter + MAX_VALUE)*sizeof(char));
if (temp == NULL) {
return NULL;
}
for (int i = 0; i < counter; i++) {
temp[i] = num[i];
}
free(num);
num = temp;
num[counter] = c;
counter++;
}
}
printf("counter = %d\n",counter);
It doesn't really matter what it does but I have some problem with the counter
. For some reason, when I insert 9876.54321
(newline at the end), It does not enters into the if (c == '\n') { break; }
block when it scanfs \n
, only on the next iteration. The length of 9876.54321
is 10
but it will print 11
. What is the reason? I also tried to switch to getchar()
but I get the same thing.