Reputation: 31
I want my code to receive an endless stream of input until the user (or text file) returns EOF. The problem is that in both input cases the first character registered is some additional one. Case in point - the input was Applepie, why is the first character registered 'p'?
Code:
string = (char *) malloc(allocated);
while (c != EOF){
c = getchar();
if (counter >= allocated -1){
allocated *= 2;
new_buffer = realloc(string, allocated );
if (! new_buffer){
return (char *) string;
}
string = new_buffer;
}
/*store the char*/
string[counter] = c;
counter++;
/*printf("current char: %c\n", string[counter]);*/
}
string[counter] = '\0';
return (char*)string;
}
Upvotes: 0
Views: 130
Reputation: 181714
This has been discussed extensively in comments. It is because getString()
writes the EOF
indicating the end of the input into the string. It should avoid doing that by checking for EOF before putting the character just read in the string.
Case in point - the input was Applepie, why is the first character registered 'p'?
Because of this:
int counter = 1; /*prints new line every 10 characters*/
[...]
char c = string[counter];
printAndSum()
then proceeds to print c
, provided that its value is not -1, so if it prints anything at all then the first character it prints will be the one at index 1. After that, it updates c
on each loop iteration with
c = string[index++];
, which has the effect of starting at the beginning of the string on the second iteration. There are various ways you could fix that, but one of the least disruptive would be to change the initialization of c
to
char c = string[0]; // or string[index]
, and to change the update of c
to use preincrement instead of postincrement:
c = string[++index];
Upvotes: 1