I am writing a C program to remove empty spaces at the end of lines of the inputted text. The sudo code is as follows,
Read in each character into a character array
Loop backwards through the array
After encountering a '\n' remove any preceding spaces until a number/alphabetical character is found
In order to do this I am writing a function to return the length of an array, so the program knows where to start from when looping backwards.
It is this length function which seems to be behaving strange.
Most of the time it works. I click build&run in code blocks. A console pops up and I enter some text, then hit CTR+D and a number is returned denoting the length of all the characters inputted into the console.
If I enter 123
, the program returns 3, makes sense. And if I enter 12 ENTER
, the program returns 3, which also makes sense as in C this is 1,2,'\n'
.
But for some reason if I enter 123 ENTER
, the program returns 5, when I expect 4 (1,2,3,'\n'
).
This is only the case for three characters and a new line, as far as I can tell.
Any idea why?
My code:
#include <stdio.h>
#define MAX 1000
int array_length(char array[]);
int main()
{
int i, c;
char condensed_array[MAX];
i = 0;
while((c=getchar()) != EOF){
condensed_array[i] = c;
++i;
}
printf("\n%d", array_length(condensed_array));
return 0;
}
int array_length(char s[])
{
int j;
j=0;
while(s[j] != '\0')
++j;
return j;
}