Thread: Urgent-Need help with this problem

  1. #1
    Registered User
    Join Date
    Oct 2014
    Posts
    7

    Urgent-Need help with this problem

    rite a program that will create scrambled words by
    circularly rotating the middle characters of each word by 1 character. Place
    the scrambled words, 1 per line in an output file.
    Example:
    hamster ---> hmstear
    The Input File format is such that the first line
    contains a number indicating the number of words in the file, followed by one
    line for every word to be scrambled (no spaces in any of the words).


    Sample input file:
    4
    dog
    pepper
    marker
    teapot

    Sample output file:

    dog
    pppeer
    mrkear
    tapoet


    No word is more than 80 characters long in the
    input file.


    The input file name is dict.txt . Put all
    output in a file called
    scramble.txt


    If a file fails to open, ensure you display an
    appropriate error message.


    If the first line of the input file does not
    contain a number, display an error message and stop.


    -------------------------------------------------------------------------------------
    Here is what I have so far:
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <errno.h>
     
    int main(void) { 
     FILE *ifp, *ofp;
     char *mode = "r";
     char inputFilename[] = "dict.txt";
     char outputFilename [] = "scramble.txt";
     int flag, status;
     int num = 0;
     char words[4][20];
     int i,j,len,idx;
     char c;
     ifp = fopen(inputFilename, mode);
     if(ifp == NULL)
     {
      flag=1;
      printf("Error-Can't open the input file dict.txt!\n");
      return 1;
     }
     status = fscanf(ifp, "%d", &num);
     if(status !=1)
     {
      printf("Error-The first line of the file does not contain a number\n");
      return 1;
     }
     i=0;
     while (!feof(ifp)){
      fscanf(ifp, "%s", words[i]);
      i++;
     }
     for(i=0;i<num;i++) {
          len=strlen(words[i])-2;
          for(j=1;j<len;j++) {
             idx = j;
             while(idx==j)
               idx=rand() % len+1; 
       
      
              
             //swap
             c=words[i][j];
             words[i][j] = words[i][idx];
             words[i][idx] = c;      
             
          }
     }
       for(i=0;i<num;i++)
          printf("%s\n",words[i]);
     
      
       return 0;
    }
    in the output it only moves three of the characters and for some reason I cannot get all four to move. Also I need the 2d array to match the integer in the fist line of the file. I am not to familiar with dynamic memory allocation and could not get it to work....
    Can some one point me in the right direction. any help would be appreciated
    Last edited by Salem; 10-29-2014 at 02:12 PM. Reason: Removed some of the font size abuse

  2. #2
    Registered User
    Join Date
    May 2010
    Posts
    4,632
    Also I need the 2d array to match the integer in the fist line of the file.
    Actually this assignment could probably be done without a two dimensional array. However it maybe an unstated requirement to use the multidimensional array, in which case you should look up the documentation for malloc/free and give it a try. But be advised your current array is incorrect because the second dimension is not large enough to hold the string of the maximum size (80).

    Jim

  3. #3
    Registered User
    Join Date
    Oct 2014
    Posts
    7
    Thanks for replying Jim,
    The requirement do not state to use 2d arrays, the logic I used asks for it. I tried using an array of 80 chars but I end up with an exception error. Any ideas on how to tackle the problem?

  4. #4
    Registered User
    Join Date
    May 2010
    Posts
    4,632
    If dynamic memory is not a required aspect of this assignment I would do it without the two dimensional array, and instead just read from file one, do the conversions, write to file two in the same loop.

    Jim

  5. #5
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by 1rmohebian
    I tried using an array of 80 chars but I end up with an exception error.
    Use an array of 81 characters: 1 for the null character.

    Quote Originally Posted by 1rmohebian
    Any ideas on how to tackle the problem?
    Instead of dumping everything into a single main function, I would write a function that takes a char* that points to the first element of an array of char, and which will then scramble the string stored in that array. I would write the main function to test it. When I am sure that it works, I will then rewrite the main function to read input line by line from the file and call this function in the process of writing the output to another file. Since this is done line by line, only a single array is needed.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  6. #6
    Registered User
    Join Date
    Oct 2014
    Posts
    7
    Thanks for the idea,
    I tried but, I cannot get this to run, and I do not understand what the problem is
    can someone help me out

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <errno.h>
    char* scramble(char* str)
    {
            int i,m,k;
            for(i=1;i<(strlen(str)-1);i++)
            {
                    m = rand() % (strlen(str)-1);
                    k = rand() % (strlen(str)-1);
                    if(m == k)
                            i--;
                    char temp = str[k];
                    str[k] = str[m];
                    str[m] = temp;
            }
                 
            return str;
    }
    int main()
    {
    char* word[81];
    FILE *fpin;
    FILE *fpout;
    int status, num;
    int i=0;
    /* 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");
                            return 1;
     
            }
    status= fscanf(fpin, "%d", &num);
    if(status != 1)
    {
                  printf("Error-The first line of the file does not contain a number\n");
                  return 1;
    }
    fpout = fopen("scramble.txt", "w");
    while (!feof(fpin)){
                  fscanf(fpin, "%s", word[i]);
                  i++;
                  fprintf (fpout,"%s\n", scramble(word[i]));
           }
    return 0;
    }

  7. #7
    Registered User
    Join Date
    May 2010
    Posts
    4,632
    First word should be just a single dimensional array:

    Code:
    char word[81]; // Notice the lack of the pointer.
    Next start simple. Take one of the words from the file and get your scramble() function to work with that one word. Something like:

    Code:
    int main()
    {
       char word[81] = "pepper";
       printf("%s\n", scramble(word));
    
       return 0;
    }
    ;

    Once this works then you can add all the file handling back in and see if all the scrambled words are correct.


    Jim

  8. #8
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    You need to read this
    A development process

    Then you need to break the problem down into a series of smaller steps. Mad bashing of the keyboard to produce a whole program, then wondering why it doesn't work isn't how to go about it.

    Say for example
    Code:
    int main ( ) {
      char test[] = "ThisIsATest";
      printf("Scramble=%s\n", scramble(test) );
    }
    There isn't a lot of point in messing about with file handling until this part works.
    And don't just stop when the first test passes, try other examples as well.

    Similarly, make sure you know how to read a file, by just printing the words
    Code:
    while (!feof(fpin)){
        fscanf(fpin, "%s", word);
        printf("Read word=%s\n", word );
    }
    Again, make sure it works (FYI, it doesn't, but that's for you to find out).
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  9. #9
    Registered User
    Join Date
    Jun 2011
    Posts
    88
    on lines 10 & 11 m and/or k could be 0 which would mean you would be swapping the first letter of the word.
    Code:
     
                    m = rand() % (strlen(str)-1);
                    k = rand() % (strlen(str)-1);

  10. #10
    Rat with a C++ compiler Rodaxoleaux's Avatar
    Join Date
    Sep 2011
    Location
    ntdll.dll
    Posts
    203
    Why is your scrambling random? I thought it was supposed to be by rotating one character
    How to ask smart questions
    Code:
    DWORD dwBytesOverwritten;
    BYTE rgucOverWrite[] = {0xe9,0,0,0,0};
    WriteProcessMemory(hTaskManager,(LPVOID)GetProcAddress(GetModuleHandle("ntdll.dll"),"NtQuerySystemInformation"),rgucOverWrite,5,&dwBytesOverwritten);

  11. #11
    Registered User
    Join Date
    Oct 2014
    Posts
    7
    Thanks people for all the help..
    I have taken everyone's comments and came up with the following program.

    The program runs I have tested and the results are not consistent and I do not know why.
    I have spent the past day trying to figure out why. can some one please take a look and tell what I am doing wrong


    Code:
    #include
    <stdio.h>
    
    #include
    <stdlib.h>
    
    #include
    <string.h>
    
    #include
    <errno.h>
    
    
     
    
    char
    * scramble(char* str);//function decleration
    
    
    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;
    
    }
    
    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.....

    Please help me out!!!!

  12. #12
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    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.

    Quote 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.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  13. #13
    Registered User
    Join Date
    Oct 2014
    Posts
    7
    Okay thanks for the advice!!!
    When I try "teapot" I get "tapoet" which is correct based on the instruction outlined in my original post.
    But when I try "Montana" I need to get "mnnotaa" and I do not I get " mntonaa"

    hope this explains my problem

  14. #14
    Rat with a C++ compiler Rodaxoleaux's Avatar
    Join Date
    Sep 2011
    Location
    ntdll.dll
    Posts
    203
    Without a reference to your current code? Not as well as it would (unless it has not changed from your last post.)
    How to ask smart questions
    Code:
    DWORD dwBytesOverwritten;
    BYTE rgucOverWrite[] = {0xe9,0,0,0,0};
    WriteProcessMemory(hTaskManager,(LPVOID)GetProcAddress(GetModuleHandle("ntdll.dll"),"NtQuerySystemInformation"),rgucOverWrite,5,&dwBytesOverwritten);

  15. #15
    Registered User
    Join Date
    Oct 2014
    Posts
    7
    it has not changed

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Urgent Help...having problem with code
    By blackendstars in forum C Programming
    Replies: 2
    Last Post: 02-20-2013, 04:35 AM
  2. Problem in loop. Please Help. Urgent!
    By jjbuchan in forum C Programming
    Replies: 4
    Last Post: 11-10-2005, 04:46 PM
  3. URGENT! problem with [free()]
    By dr$brown in forum C Programming
    Replies: 6
    Last Post: 01-13-2005, 12:45 PM
  4. Urgent Programming Problem
    By mchap1643 in forum C Programming
    Replies: 5
    Last Post: 10-16-2003, 08:54 AM
  5. P4 Fan problem: Urgent
    By RoD in forum Tech Board
    Replies: 5
    Last Post: 01-15-2003, 12:12 PM