1

I want to take a string and output it without spaces. I wrote the code below but my if statement doesn't seem to detect the spaces in the char string or I am not doing this right.

I assume that my problem is in my if statement but I don't know how to fix it.

int main (void)
{
  char s[50];

  printf("Enter string:");
  fgets(s,50,stdin);

  for( int i = 0; i < strlen(s); i++ ){
    if( &s[i] != " " ){
     printf("%c\n", s[i]);
    }
  }

  return 0;
}

Output:

Enter string:xales was here
x
a
l
e
s

w
a
s

h
e
r
e
Yu Hao
  • 119,891
  • 44
  • 235
  • 294
TheXales
  • 89
  • 11
  • 2
    Replace `if( &s[i] != " " ){` with `if (s[i] != ' ' ){`, the former does not what you probably think. – yeputons Feb 09 '17 at 01:59
  • `if( &s[i] != " " ){` Comparing an address of a char to a string literal? Works, but never likely to be true... See http://stackoverflow.com/questions/3683602/single-quotes-vs-double-quotes-in-c-or-c – John3136 Feb 09 '17 at 02:00
  • @yeputons if you write that as an answer il take it! Thanks! – TheXales Feb 09 '17 at 02:02

2 Answers2

0

The important thing to note is that a double-quoted character is actually a string, not a char type. This value holds a memory address to a place in your program's memory (not a value on the stack) that happens to be 2 bytes long (one for the space, one for \0). So that's thing #1: change " to ' and you'll have a single char, on the stack, to compare by value.

Thing number two is that by using the & symbol there, you are trying to compare to the address of the ith index in your string, instead of the value there. Just remove the &.

yeputons
  • 8,478
  • 34
  • 67
Chris Trahey
  • 18,202
  • 1
  • 42
  • 55
0

Yes, you are right. Your if condition is always going to be true, hence, you will be end up printing the entire string as it is.
Your if condition: if( &s[i] != ' ' ) print s [i];

Here "&" represents address. So in your if block what you are checking is:

  ` if(addressof( s[i] != ' ') print s[i]; `

Now address is never space, hence your if block will always be true. But as you want to check for s to be printed without spaces check for values: if( s[i] != ' ' ) print s [i];

Also, as you are comparing charecter wise, you should understand that, " " is for string and for characters you should use single quotes ' '.