I just picked up C and am following through The C programming language.
I've previously got experience with a lot of 'higher'-level languages, so when I saw this exercise in the book:
Write a program to copy its input to its output, replacing each string of one or more blanks by a single blank.
I thought I'd create a very basic and primitive trim-program that takes an input and removes all superfluous white-spaces (more than 1 in a row) and prints out a 'trimmed' string.
As mentioned I just recently started and we haven't covered dynamic arrays yet, so I'm just using static ones.
But I was hoping to get some feedback on my solution:
#include <stdio.h>
/*
** A primitive trimmer
** to remove any superflous
** whitespaces in a given
** string (input).
*/
int main () {
/*
** Setting up the variables
**
** Working with static
** arrays since I haven't
** been introduced to dynamic.
*/
char input [100], output[100];
fgets(input, 100, stdin);
int i = 0, k = 0;
// Looping over input until hitting
// an item containing a null-char.
while (input[i] != '\0') {
if (input[i] == ' ') { // hitting first space.
int j = i + 1; // initiating temporary counter.
if (input[j] != '\0') {
// find index of first non-space
// character after initial space.
while (input[j] != '\0' && input[j] == ' ') {
if (input[j] == ' ') {
i++; // keep indexing input-index
}
j++; // keep incrementing temporary indexer.
}
}
}
output[k] = input[i]; // insert non-space item into output.
i++; // increment input-indexer.
k++; // prepare output-indexer for next non-space.
}
printf("%s", output); // print trimmed input.
}
It's not going to be pretty and you might not like it, but please keep in mind that I am new to the language!
I'd like to get feedback on my overall solution, any thoughts on the baseline algorithm and how well I'm following best (syntactical) practices.
getchar
andputchar
? \$\endgroup\$getchar
andputchar
only works on characters. \$\endgroup\$