Thread: Struggling with Reverse of String

  1. #1
    Registered User
    Join Date
    Nov 2008
    Posts
    110

    Struggling with Reverse of String

    So I am writing a program that reverses any given input of strings..
    however it looks weird..it produces a new line under the given input then prints the reverse of the string. I am also able to type next to the reversed string which shouldn't happen. I should be able to type in the line under it. Help much appreciated!

    Here is a mini example...
    Code:
    123
    
    321[i can type right next to this output]
    Code:
    #include <stdio.h>
    #define UNLIMITED 10000
    
    int getline(char line[]);
    void reverseCopy(char to[], char from[]);
    
    //prints lines without blanks or tabs
    //delete lines that are completely blank
    main(){
    	int len; //current line length
    	char line[UNLIMITED]; //current input line
    	char newLine[UNLIMITED]; //the new line
    	
    	//while len is greater than 0
    	//means there was a line
    	while ((len = getline(line)) > 0){
    		reverseCopy(newLine, line);
    		printf("%s", newLine);
    		}
    }
    
    //copy from into to reversed
    void reverseCopy(char to[], char from[]){
    	int i, revI;
    	char tmp[100];
    
    	i = revI = 0;
    
    	while (tmp[i] = from[i] != '\0'){
    			i++;
    		}
    	
    	if (from[i] == '\0'){
    		//from[i] would equal to '\0'
    		//so i would have to copy from 
    		//1 less of i
    		while(i != 0){
    			to[revI] = from[i - 1];
    			++revI;
    			--i;
    		}
    	}
    
    	to[revI] = '\0';
    }
    
    //read a line into s, return length
    int getline(char s[]){
    	int c, i;
    
    	for(i = 0; (c = getchar()) != EOF && c != '\n'; ++i)
    		s[i] = c;
    	if(c == '\n'){
    		s[i] = c;
    		++i;
    	}
    	s[i] = '\0';
    	return i;
    }

  2. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    So the \n is part of the string, and it gets reversed too. So your new string starts with a new line, and does not end with one.

  3. #3
    Registered User
    Join Date
    Nov 2008
    Posts
    41
    Quote Originally Posted by tabstop View Post
    So the \n is part of the string, and it gets reversed too. So your new string starts with a new line, and does not end with one.
    That's right so you should just do something like not copy over any newlines and add a newline on the end or something like that.

    Also I just thought I'd point out in here
    Code:
    while (tmp[i] = from[i] != '\0'){
    			i++;
    		}
    	
    	if (from[i] == '\0'){
    that after the while loop you can be sure that from[i] == '\0' so you don't need the if. Totally pointless either way but I'm into that sort of thing.

  4. #4
    Registered User
    Join Date
    Nov 2008
    Posts
    110
    Oh..alright..Thanks for the help guys. I solved all of the problems but one more came up. My reversed string now has a weird char at the end. I don't see why though...

    Code:
    #include <stdio.h>
    #define UNLIMITED 10000
    
    int getline(char line[]);
    void reverseCopy(char to[], char from[]);
    
    //prints lines without blanks or tabs
    //delete lines that are completely blank
    main(){
    	int len; //current line length
    	char line[UNLIMITED]; //current input line
    	char newLine[UNLIMITED]; //the new line
    	
    	//while len is greater than 0
    	//means there was a line
    	while ((len = getline(line)) > 0){
    		reverseCopy(newLine, line);
    		printf("%s", newLine);
    		}
    }
    
    //copy from into to reversed
    void reverseCopy(char to[], char from[]){
    	int i, revI;
    	char tmp[100];
    
    	i = revI = 0;
    
    	while (tmp[i] = from[i] != '\0'){
    			i++;
    		}
    		//from[i] would equal to '\0'
    		//so i would have to copy from 
    		//1 less of i
    		while(i != 0){
    			to[revI] = from[i - 2];
    			++revI;
    			--i;
    		}
    	to[revI] = '\n';
    	to[revI + 1] = '\0';
    }
    
    //read a line into s, return length
    int getline(char s[]){
    	int c, i;
    
    	for(i = 0; (c = getchar()) != EOF && c != '\n'; ++i)
    		s[i] = c;
    	if(c == '\n'){
    		s[i] = c;
    		++i;
    	}
    	s[i] = '\0';
    	return i;
    }

  5. #5
    Registered User
    Join Date
    Nov 2008
    Posts
    41
    Because of the second while loop, which reads backwards, you grab a character from before the beginning of the string, ie. from[-1], when i == 1. Set it to
    Code:
    while(i > 1){

  6. #6
    Registered User
    Join Date
    Nov 2008
    Posts
    110
    Nice! i finally finished this section! Thanks all!

  7. #7
    Registered User
    Join Date
    Nov 2008
    Posts
    110
    Hm..so I was just thinking and I think I want to get this clarified about arrays of chars.
    So when I type in something and it turns into an array, how does that array look?

    Correct me if I'm wrong..

    I have an array Z[100];
    which can contain 100 elements.

    Suppose I typed in ABC.

    It gets put into the array
    Z[0] = A, Z[1] = B, Z[2] = C, Z[3] = '\n', Z[4] = '\0'

    Is that how it looks? Is '\0' equivalent to null? How would EOF relate to this '\0' char? Is this '\0' sign at the end of every line, or the end of the entire input, say a whole paragraph of 5 lines? What would Z[5], Z[6],....Z[100] contain? I hope this can be clarified. Thanks!

  8. #8
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    If you used a for loop to put the letter into the char array, it might go in that way. It could also go in reverse order, depending on how the for loop or while loop, is set up.

    Some functions in C will put an end of string '\0' marker in for you, others won't. It's up to you as the programmer to ensure what's what.

    What the rest of Z[] might contain all depends:

    1) Global char array's on the stack, (before any functions), are initialized to "".
    2) Char array's inside a function and malloc'ed, may have any random value.
    3) Char array's inside a function and calloc'ed, will be all set to "" (the empty string).

    Hope that helps.

  9. #9
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,057
    Yes, you have it more or less right: entering "abc" followed by pressing the enter key would result in the data 'A', 'B', 'C', '\n', '\0' being stored in whatever string you read the input into. (Note my quotes.)

    A '\0' occurs at the end of every string. It's there so that functions like strcmp() and printf() know where the string ends. So how often it occurs depends on how many strings you have. If you had one string for every line in the file, for example (a common occurence), then you'd also have one '\0' at the end of every string. If you put all of the data from a file into one big string (better make sure you have enough space!), there would only be one '\0', at the end of the data.

    Note that this means you can truncate a string just by adding a '\0' to it.
    Code:
    char greeting[] = "Hello";
    greeting[2] = '\0';
    // Now greeting effectively contains "He", according to just about every C and C++ function
    This '\0' character is sometimes called the NULL terminator; it's equivalent in all ways to the number 0, basically. (Except that '\0' has type char instead of type int.) So you could use, for example,
    Code:
    string[i] = 0;
    to terminate a string.

    Do be careful with your use of the word "NULL", however: when referring to pointers, it's not the same thing, really. A pointer is NULL when it doesn't point to anything. Almost all of the time, this is equivalent to saying that the pointer has the value 0, so it would seem quite similar to the NULL terminating character '\0'. But it's not the same; '\0' is a char, NULL is of a pointer type. (0 can be used in both cases.)

    EOF is another matter. EOF is actually not a character; it's of type int. EOF is used to signify that the end of a stream has been reached. However, you shouldn't try to stuff EOF into a character, because then EOF will correspond with an actual valid character in the file. For example, if EOF is -1 (which it frequently is), and you're reading unsigned chars, that will become 255, which could actually occur in the file. (And if it did, your program would think it had reached the end of the file when it actually had not.)

    So anyway, that's why you might see code like this:
    Code:
    int c;  // the character read -- use int in case of EOF
    int n = 0;  // the number of characters read
    char data[BUFSIZ];
    while(n < BUFSIZ && (c = getchar()) != EOF) {
        data[n ++] = c;
    }
    data[n] = 0;  // add the NULL terminator
    Anyway, hopefully this long rambling post contains some answers you were looking for. If something seems fuzzy, just ask.
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  10. #10
    Registered User
    Join Date
    Nov 2008
    Posts
    110
    Great answers! but I still have a few questions..

    So doing string[i] = 0 would end/truncate the string? Whats the difference between that and string[i] = '\0'? What if I wanted to use the char 0('0')?
    Would I do string[i] = '0'?

    Also with that hello example, would that new array look like
    'h', 'e', '\0', 'l', 'l', 'o'. Or having a '\0' simply "wipes" everything after it?

    Also if I had an array of size 10, and I gave it 'a', 'b', 'c'. array[3] being '\n', array[4] being '\0'. What is within array[5], ..[6], up to [10]?

    Thanks for the answers!

  11. #11
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by dnguyen1022
    So doing string[i] = 0 would end/truncate the string?
    It would simply mark the end of a string, like how a full stop marks the end of a sentence.

    Quote Originally Posted by dnguyen1022
    Whats the difference between that and string[i] = '\0'?
    0 is an integer const, '\0' is a character constant. They both are of type int and have the same value. (However, if you ever use C++, note that '\0' would then be of type char.)

    Quote Originally Posted by dnguyen1022
    What if I wanted to use the char 0('0')?
    Would I do string[i] = '0'?
    Yes since '0' is also a character constant, but it does not have the value of 0 (in ASCII, it has the value of 48).

    Quote Originally Posted by dnguyen1022
    Also with that hello example, would that new array look like
    'h', 'e', '\0', 'l', 'l', 'o'.
    Yes.

    Quote Originally Posted by dnguyen1022
    Or having a '\0' simply "wipes" everything after it?
    No.

    Quote Originally Posted by dnguyen1022
    Also if I had an array of size 10, and I gave it 'a', 'b', 'c'. array[3] being '\n', array[4] being '\0'. What is within array[5], ..[6], up to [10]?
    If you initialise that array with "abc\n" then array[5] onwards would be '\0'. However, if you assign characters individually, then array[5] onwards would contain whatever was already there, which could be "garbage" if the array was not initialised.
    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

  12. #12
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,613
    The character '0' represents the digit zero. The character '\0' represents the numerical zero and is the one that acts as a sentinel value for the end of a C-string. The bit patterns for these two characters are never equivalent and one will not do the job of another.

    Now, for your other question:
    string[i] = 0;
    This statement relies on type coercion. In short, even though the literal zero is written the compiler will store the null terminator as that is the proper representation.

    Relying on type coercion is not smart, imo, if you are using even a remotely type strict language. This case is not one of them, but there are situations where type coercion should be avoided to prevent error. It's best not to fall into any habits in the early stages of your C programming.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 8
    Last Post: 04-25-2008, 02:45 PM
  2. We Got _DEBUG Errors
    By Tonto in forum Windows Programming
    Replies: 5
    Last Post: 12-22-2006, 05:45 PM
  3. Program using classes - keeps crashing
    By webren in forum C++ Programming
    Replies: 4
    Last Post: 09-16-2005, 03:58 PM
  4. Classes inheretance problem...
    By NANO in forum C++ Programming
    Replies: 12
    Last Post: 12-09-2002, 03:23 PM
  5. ........ed off at functions
    By Klinerr1 in forum C++ Programming
    Replies: 8
    Last Post: 07-29-2002, 09:37 PM