int vs size_t
###int vs size_t
AccordinglyAccordingly to the c language specification, it's highly recommendable to use size_t
as the type for index variables. So in your case...
int i = 0, k = 0;
should be:
size_t i = 0, k = 0;
if
condition repeats while
condition
###if
condition repeats while
condition
II was a bit confused by this piece of code
while (input[j] != '\0' && input[j] == ' ') {
if (input[j] == ' ') {
i++; // keep indexing input-index
}
j++; // keep incrementing temporary indexer.
}
Specifically the if
condition - it will always be true due to the while
condition logic. So, as result, variable j
just duplicates i
with an invariant j = i+1
.
Lack of null character
###Lack of null character
IfIf you test your code on any string input, you will notice that the program prints some strange characters after your result. It happens because you didn't copy the \0
character to the output
array.
Taking all this into an account (as well as @pacmaninbw's and @holroy's recommendations)
#include <stdio.h>
#include <ctype.h>
#define MAX 100
int
main ()
{
char input [MAX], output[MAX];
fgets(input, MAX, stdin);
size_t inputIndex = 0, outputIndex = 0;
while (input[inputIndex] != '\0')
{
output[outputIndex++] = input[inputIndex];
if (input[inputIndex] == ' ')
while(input[++inputIndex] == ' ')
;
else
inputIndex++;
}
output[outputIndex] = '\0';
printf("%s", output);
}