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
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 i
th index in your string, instead of the value there. Just remove the &
.
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 ' '.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.