Thread: Read in a file, reverse string, print on multiple lines base on command prompt entry

  1. #1
    Registered User
    Join Date
    Oct 2016
    Posts
    4

    Question Read in a file, reverse string, print on multiple lines base on command prompt entry

    I need to be able to read in a file, and reverse the words (mirror writing), based on what is entered on the command prompt. The data can be either left-aligned, centered, or right-aligned.

    For Example:

    I have a file called reverse.txt that holds the following line:

    The quick green owl flies over the small old cat.

    So, if in the command prompt entry is:

    ./reverse.c reverse.txt L15

    The output needs to look like this....

    neerg kciuq ehT
    revo seilf lwo
    dlo ynit eht
    .tac

    Any help will be greatly appreciated.

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    So what are you actually stuck on?
    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.

  3. #3
    Registered User
    Join Date
    Oct 2016
    Posts
    4
    This is what I have so far...


    Code:
    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    
    
    #define MAXC 256
    int wordslength;
    
    
    FILE *fname;
    
    
    int main(int argc, char *argv) {
    char str[MAXC];
    int i;
    int x;
    int y;
    int z;
    char **words = NULL;
    char buf[wordslength + 1];
    int *n;
    int nwords = 0;
    int maxlen = MAXC > 0 ? MAXC : 1;
    int rows;
    
    
    fname = fopen(argv[1], "r");
    
    
    while(fgets(str, wordslength + 1, fname)) {
    for(x = wordslength; x >= 0; x--) {
    printf("%c", str[x]);
    }
    
    
    printf("\n");
    }
    
    
    fclose(fname);
    return 0;
    }

    Issues I am having:


    1. Cannot figure out how to assign the 15 from L15 from command prompt to the wordslength variable (if that variable is being used correctly).
    2. The out put is not displaying correctly. It is doubling the third line.
    nworb kciuq ehT
    revo spmuj xof
    d dlo yzal eht
    d dlo yzal
    .go
    4. With the above out put, words cannot be broken (example: the word 'god' (reversed for dog)).
    5. I have try to research on google, and I have read something about storing previous word. Not sure how to do this.
    6. I am first trying to solve the left-align issue, but then need to figure out the Center and Right-align.


    I am very new to C


    If any other information is needed, please just let me know.
    Last edited by ccg; 10-18-2016 at 01:26 PM.

  4. #4
    Registered User
    Join Date
    Sep 2014
    Posts
    364
    This is wrong. You should become a warning from your compiler.
    Code:
    int main(int argc, char *argv) {
    It should look like:
    Code:
    int main(int argc, char *argv[]) {
    Why is the variable 'wordslength' and 'fname' global?
    You can declare it in main.
    And the variable 'wordslength' will be initialized to 0, because its global.
    Later, you use it (on line 20) without set it to another value.
    This means, your char buf[] has a size of 1 byte.
    You should check if the file was successfully opened.
    Code:
    …
        if ((fname = fopen(argv[1], "r")) == NULL) {
            fprintf(stderr, "could not open file '%s'! exit.\n", argv[1]);
            exit(1);
        }
    …
    I would read the complete line and cut it in sequences.
    After that, you can output every sequence in reverse order.
    For middle- and right-oriented, count the characters of the sequence and output the difference as space right befor the sequence.
    So, have you a sequence of 11 characters and a max length of 15:
    right-oriented: output 4 space first
    middle-oriented: output 2 space first
    Last edited by WoodSTokk; 10-18-2016 at 06:31 PM.
    Other have classes, we are class

  5. #5
    Registered User
    Join Date
    Oct 2016
    Posts
    4
    WoodSTokk, thank you for the reply.

    I am not sure how to cut the line into sequences. Can you explain a little more.

    Can you explain the center and right align a little more as well.

    Here is what I have now with the additions of your suggestions.

    Code:
    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    #include <ctype.h>
    
    
    #define MAXC 256
    
    
    int main(int argc, char *argv[]) {
    
            int wordslength;
    	sscanf(argv[2], "%*[^0123456789]%d", &wordslength);
    
            FILE *fname;
    	char str[MAXC];
    	int i;
    	int x;
    	int y;
    	int z;
    	char **words = NULL;
    	char buf[wordslength + 1];
    	int *n;
    	int nwords = 0;
    	int maxlen = MAXC > 0 ? MAXC : 1;
    	int rows;
    	
    	//sscanf(argv[2], "%*[^0123456789]%d", &wordslength);
    
    
    	//printf("%d\n", wordslength);
    	//printf("%c\n", buf);
    
    
    	file = fopen(argv[1], "r");
    
    
    	if((fname = fopen(argv[1], "r")) == NULL) {
            fprintf(stderr, "could not open file '%s'! exit.\n", argv[1]);
            exit(1);
        }
    
    
    	while(fgets(str, wordslength + 1, file)) {
    		
    		//y = strlen(str);
    		//y = strlen(buf);
    
    
    		/*if(buf[y - 1] == '\n')
    			buf[--y] = 0;
    
    
    		words[(*n)++] = strdup (buf);*/
    
    
    		/*if (*n == maxlen) { //realloc as required, update maxlen
    			void *tmp = realloc (words, maxlen * 2 * sizeof *words);
    
    
    		words = tmp;
    		memset (words + maxlen, 0, maxlen * sizeof *words);
    		maxlen *= 2;
    
    
    		}*/
    
    
    		for(x = wordslength; x >= 0; x--) {
    			printf("%c", str[x]);
    		}
    		printf("\n");
    
    
    	}
    
    
    	/*if(!(words = calloc(maxlen, sizeof*words))) {
    		fprintf(stderr, "getwords() error: virtual memory exhausted.\n");
    		return NULL;
    	}*/
    
    
    	/*while(fgets(buf, wordslength + 1, file)) {
    		size_t wordlen = strlen(buf);
    
    
    		if(buf[wordlen - 1] == '\n') {
    			buf[--wordlen] = 0;
    
    
    		if(*n == maxlen) {
    			void *tmp = realloc(words, maxlen* 2* sizeof *words);
    
    
    			//if(!tmp) {
    				//fprintf(stderr "getwords() realloc: memory exhausted.\n");
    				//return words;
    			//}
    			words = tmp;
    			memset(words + maxlen, 0, maxlen* sizeof *words);
    			maxlen*=2;
    		}
    		}
    		//return words;
    
    
    		//fclose(file);
    
    
    		printf("\n '%d' lines read from '%s'\n\n", nwords, file);
    
    
    		for(i=0; i < nwords; i++) {
    			printf("%s\n", words[i]);
    		}
    
    
    		//fclose(file);
    
    
    		//return 0;
    	}*/
    
    
    	fclose(file);
    	return 0;
    }
    The for loop is actually returning the code reversed but still not correctly. I think it goes back to the sequence thing you spoke about.

    The commented out code is stuff I am playing with but can't get to work correctly.

  6. #6
    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 step back and plan how to write the code in a series of small steps, each of which builds on previous progress.

    Simply hacking away at an increasingly large main() will get you nowhere.

    Eg.
    Read and print all the words.

    Input "The quick green owl flies over the small old cat."
    Output
    found word "The"
    found word "quick"
    found word "green"
    found word "owl"
    ...

    Until you can read words reliably, stressing over reversal and formatting is a waste of time.

    Then you try say reversing the words
    Input "The quick green owl flies over the small old cat."
    Output
    found word "ehT"
    found word "kciuq"
    found word "neerg"
    found word "lwo"

    Now think how you would break the rest of the problem down into achievable steps.
    If you start a step and it seems too complicated, then break it down some more.

    When your code for a given step is working, then make a copy of it so you always have something to go back to.
    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.

  7. #7
    Registered User
    Join Date
    Oct 2016
    Posts
    4
    Thank you for the reply Salem. I will try to do as you suggested.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 6
    Last Post: 08-08-2015, 04:12 AM
  2. How to read multiple lines of input
    By veera in forum C Programming
    Replies: 4
    Last Post: 06-28-2015, 11:52 PM
  3. Replies: 3
    Last Post: 02-28-2014, 01:51 PM
  4. Read command line and write to file or string
    By miiisuuu in forum C Programming
    Replies: 1
    Last Post: 10-21-2007, 11:39 AM
  5. read multiple lines from a file
    By YankeePride13 in forum C Programming
    Replies: 2
    Last Post: 11-10-2005, 10:30 PM

Tags for this Thread