TheWaveLad
TheWaveLad

Reputation: 1016

Ignore whitespaces with isspace and getchar()

I want to read numbers from the command line with getchar(), remove all whitespaces with isspace() and print them with putchar() . However, the following code does not remove any whitespaces. The input 10 1 leads to an output 10 1.

Can you help me finding my mistake? Thank you!

int main(void){

    char input[UINT_MAX];
    int i = 0;
    while ( i < UINT_MAX && (input[i] = getchar()) != '\n' && !isspace(input[i])){
        i++;
    }
    if ( i == UINT_MAX ) {
        printf("Too long");
    }
    else {
        input[i] = '\0';
    }
    i = 0;

    while( input[i] ) {
        putchar(input[i]);  
        i++;
    }

    return 0;
}

Note that I'm not allowed to use any extra headers. I'm restricted to the above functions.

Upvotes: 1

Views: 1933

Answers (2)

gnometorule
gnometorule

Reputation: 2139

The shortest way to fix your code (after making the array bound a reasonable smaller value, as mentioned in comments) is to remove the isspace() from the loop condition, and instead add it before i++ inside the loop body as

  if isspace(input[i]) continue          

As is, you stop processing when you find a ws. Instead, move to the next input character by forwarding, while not increasing i. You also should remove the redundant check if i == bound, so what is currently in the else clause is always executed (if the last character was ws, it needs to be overwritten by '\0').

Upvotes: 2

ooga
ooga

Reputation: 15501

Allocating 4 gigabytes for your character array is crazy! Pick some reasonable value and define a constant for it.

#include <stdio.h>
#include <ctype.h>

#define MAX_INPUT 10000

int main() {
  char input[MAX_INPUT + 1];
  int i = 0, c;

  while (i < MAX_INPUT && ((c = getchar()) != EOF) && c != '\n')
    if (!isspace(c))
      input[i++] = c;
  input[i] = '\0';

  for (i = 0; input[i]; i++)
    putchar(input[i]);
  putchar('\n');

  return 0;
}

Upvotes: 0

Related Questions