Hi
I wrote this to swap characters in a string. as long as the string is even in legnth, it works fine. But when it is odd it prints the last character on a new line and a ascii character. I know it is because the last character does not have anything to swap with. My goal is to just print the last character at the end if it is odd. I know I need modulus but van;t figure out where.
Code:
#include "string.h"
#define MaxStringLen 200
int main(int argc, char* argv)
{
char userString[MaxStringLen + 1];
char *copyString;
int size;
int i;
printf( "Please enter some text: ");
fgets(userString, sizeof(userString), stdin);
size = strlen(userString);
copyString = malloc(size + 1 * sizeof(char));
for (i = 0; i < size + 1; i += 2)
{
copyString[i] = userString[i + 1];
copyString[i + 1] = userString[i];
}
printf( "Here is the string you entered and its byte-swapped counterpart:\n");
printf( " %s", userString);
printf( " %s\n", copyString);
free(copyString);
copyString = NULL;
return 0;
}