Search code examples
cstringnewlinewhitespacec-strings

Removing a newline from the middle of a string using getchar


Right now I have a string looking like this:

A sentence        
with a newline.

I'm reading the string in via console input like so:

ch = getchar();

while (ch != '.') {
  msg[i] = ch;
  i++;
  ch = getchar();
}

And, after reading it in, I remove the whitespace present by doing this in a function and applying to the msg char array:

char *remove_white_spaces(char *str) {
    int i = 0, j = 0;
    while (str[i]) {
        if (str[i] != ' ')
      str[j++] = str[i];
        i++;
    }
    str[j] = '\0';
    return str;
}

I've tried looping over it and stopping at \n but that leaves an output of "Asentence", as the string terminates as the \n is set to 0.

Whole main:

int main(void) {
  char msg[MAX_MSG_LEN+1];
  char ch;
  int i = 0;
  ch = getchar();

  while (ch != '.') {
    msg[i] = ch;
    i++;
    ch = getchar();
  }

  msg[i] = '.';
  msg[i + 1] = '\0';
  remove_white_spaces(msg);

  printf("%s\n", msg);
  return 0;
}

Solution

  • Following the suggestion of @MarkBenningfield I did the following and checked for '\n' and just replaced it with a space.

    while (ch != '.') {
      msg[i] = ch;
      i++;
      ch = getchar();
    
      if (ch == '\n') {
        ch = ' ';
      }
    }