Several problems:
NEVER NEVER NEVER NEVER NEVER NEVER use gets
. First of all, it's deprecated as of C99, and will be gone from the next revision of the standard. Secondly, it will introduce a point of failure in your code (not may introduce, will introduce). Instead of gets(str)
, use fgets(str, sizeof str, stdin)
instead.
Use character constants instead of numeric values, because all the world is not ASCII:
if (str[i] == ' ') // not str[i] == 32
Whitespace includes tabs, form feeds, returns, etc., not just spaces; instead of checking against individual values, use the isspace()
library function.
The following lines are a problem:
str[i++] = str[i];
str[i] = str[i++];
First of all, this should invoke undefined behavior; you're attempting to read and update an object more than once between sequence points. Second, I'm not sure of the logic. It looks like you're trying to swap elements, instead of just skipping over one.
You're passing an integer value to strlen
: that's not going to work. It's going to interpret that integer value as an address (you should at least be getting a warning), with potentially bad results.
You can do this in a single loop with two array indices:
#include <stdio.h>
#include <ctype.h>
int main(void)
{
char str[15];
if (fgets(str, sizeof str, stdin) != NULL)
{
size_t r, w;
printf("Original: \"%s\"\n", str);
/**
* str[r] is the element that we are reading; str[w]
* is the element that we are writing
*/
for (r = 0, w = 0; str[r] != 0; r++)
{
if (!isspace(str[r])) // if str[r] is not a whitespace character
str[w++] = str[r]; // write it to str[w]; note that we only
// advance w for non-whitespace chars
}
str[w] = 0; // add the 0 terminator at the end
printf("Stripped: \"%s\"\n", str);
}
return 0;
}
Obviously, this alters the original string. If you need to preserve the original input for some reason, you'll have to declare a second buffer to hold the modified string.