For starters, you need to indent your code properly, e.g.,
Code:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<errno.h>
char *scramble(char *str);
int main()
{
char word[81];
FILE *fpin;
FILE *fpout;
int status, num;
/* open the input file -- quit if not found */
fpin = fopen("dict.txt", "r");
if (fpin == NULL)
{
printf("Error-Can't open the input file dict.txt!\n");
printf("Press the enter key to end program!");
getchar();
return 1;
}
/* Check to ensure that the first line of the file contains a number -- quit if not found */
status = fscanf(fpin, "%d", &num);
if (status != 1)
{
printf("Error-The first line of the file does not contain a number\n");
printf("Press the enter key to end program!");
getchar();
return 1;
}
/* open the output file */
fpout = fopen("scramble.txt", "w");
/* read one line at a time and send to scramble function and print out */
while (!feof(fpin))
{
fscanf(fpin, "%s", word);
fprintf(fpout, "%s\n", scramble(word));
}
return 0;
}
/* Scramble function receives a pointer to the array of words and returns a pointer to the same array*/
char *scramble(char *str)
{
int j, len;
char c;
len = strlen(str) - 2;
//finds the length of word excluding the first and last character
for (j = 1; j < len; j++)
{
//swap
c = str[j];
str[j] = str[j + 1];
str[j + 1] = c;
}
return str;
}
If you want to use tabs for indentation then take care to use only one tab per indent level. Otherwise, choose a consistent number of spaces (between 2 to 8; I personally prefer 4) per indent level.
It is not correct to use feof to control a loop in the way that you did. It is also not correct to use "%s" as the format string to read a string, because it does not account for the fact that the destination array is finite. Rather, you should write something like:
Code:
while (fscanf(fpin, "%80s", word) == 1)
{
fprintf(fpout, "%s\n", scramble(word));
}
Remember to close the files after you are done with them: this is a good habit. This should also happen for the input file when you end because of invalid input, although if I remember correctly the file will be closed anyway when the program terminates.
Originally Posted by
1rmohebian
The problem seems to be in my scramble function. it is not scrambling based on the requirements. I have tried everything and like I mentioned it works for the words provided in my description above but not for words that have more then 6 chars.....
I tried with "teapots" and got "tapotes", which looks correct to me. "hamster" resulted in "hmstear", which is the example that you quoted.