Thread: Using fgets, removing last character

  1. #1

    Using fgets, removing last character

    Hello,

    I have ran into a slight problem. Of course I always did it the bad way I guess and now I'm looking for a solution. Here is my current code:

    Code:
    int main() {
    	char sentence[256];
    
    	printf("Enter your sentence here: ");
    	fgets(sentence, 255, stdin);
    	sentence[strlen(sentence)-1] = '\0';
    	
    	printf("Sentence: %s\n", sentence);
    	
    	return 0;
    }
    The only thing is, I don't like calling strlen() in that situtation. I've tried everything from *(sentence--) = '\0' to sentence[*sentence-1] = '\0' and I just can't seem to find a way.

    To keep an open mind, is there actually a way or is this [current way] the best way?


    Thank you for your time,
    - Stack Overflow
    Segmentation Fault: I am an error in which a running program attempts to access memory not allocated to it and core dumps with a segmentation violation error. This is often caused by improper usage of pointers, attempts to access a non-existent or read-only physical memory address, re-use of memory if freed within the same scope, de-referencing a null pointer, or (in C) inadvertently using a non-pointer variable as a pointer.

  2. #2
    Crazy Fool Perspective's Avatar
    Join Date
    Jan 2003
    Location
    Canada
    Posts
    2,640
    fgets will automatically append the '\0' so long as there is no error in reading.

  3. #3
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Quote Originally Posted by Perspective
    fgets will automatically append the '\0' so long as there is no error in reading.
    To add to this, this is why you should check the return value of your functions...

    Quzah.
    Hope is the first step on the road to disappointment.

  4. #4
    I agree,

    Though in fact fgets returns a char * and when dealing with the function, or maybe even in Linux itself, my sentence I retrieve retrieves the '\n' at the end of the string for some strange reason.

    I will look into this with more detail.

    - Stack Overflow
    Segmentation Fault: I am an error in which a running program attempts to access memory not allocated to it and core dumps with a segmentation violation error. This is often caused by improper usage of pointers, attempts to access a non-existent or read-only physical memory address, re-use of memory if freed within the same scope, de-referencing a null pointer, or (in C) inadvertently using a non-pointer variable as a pointer.

  5. #5
    & the hat of GPL slaying Thantos's Avatar
    Join Date
    Sep 2001
    Posts
    5,681
    Well a couple things to remember
    1) fgets will get the '\n' if there is room
    2) fgets will always append a null character
    3) strlen returns the number of characters not counting the null character.

    So if the input what "able" your string would be:
    "able\n\0", strlen would return 5, 5 - 1 = 4, string[4] is '\n'

  6. #6
    I see,

    Thanks. A program I'm writing doesn't like the whole '\n' character, and my algorithm usually gets messed up if that happens, so I'm going to take another approach:

    Code:
    int main() {
    	char sentence[256], *sent;
    
    	printf("Enter your sentence here: ");
    	sent = fgets(sentence, 255, stdin);
    	sent[strlen(sentence) - 1] = '\0';
    	
    	printf("Sentence: %s\n", sent); // use sent instead of sentence from now on
    	
    	return 0;
    }
    That shouldn't conflict with sentence now, and the whole length of the string recursively calling itself. I thought there would be an easier way, but I guess this is the best way around it for now.


    Thank you for your time,
    - Stack Overflow
    Segmentation Fault: I am an error in which a running program attempts to access memory not allocated to it and core dumps with a segmentation violation error. This is often caused by improper usage of pointers, attempts to access a non-existent or read-only physical memory address, re-use of memory if freed within the same scope, de-referencing a null pointer, or (in C) inadvertently using a non-pointer variable as a pointer.

  7. #7
    Registered User linuxdude's Avatar
    Join Date
    Mar 2003
    Location
    Louisiana
    Posts
    926
    the reason that
    Code:
    *(sentence--) = '\0
    doesn't work is because the memory address is at the beggining for strings. So sentence-- will be one before the actual string. It really is the best way, because either way you will have to get to the end of a string. if you want you could use (with caution)scanf
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    int main(void){
            char string[100];
            printf("Enter a string\n");
            if(!scanf("%100s*[^\n]",string)){
                    printf("Failure\n");
                    return EXIT_FAILURE;
            }
            printf("%s",string);
            return EXIT_SUCCESS;
    }
    this won't get spaces though
    Last edited by linuxdude; 07-05-2004 at 07:55 PM.

  8. #8
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Code:
    if( (c=strrchr( buf, '\n' )) )
        *c='\0';
    With, or without the r.

    Quzah.
    Hope is the first step on the road to disappointment.

  9. #9
    Registered User
    Join Date
    Jul 2004
    Posts
    11
    forgive me my ignorance but, in this case wouldnt it be easier to use gets instead of fgets?

    Even though it dosnt have built in array overrun you could always just code in an if statement to tell it the last chr is null if it exceeds size and then you wouldnt have to worry about \n being in there and save your self a few clock cycles.

    ~Meloshski

  10. #10
    Obsessed with C chrismiceli's Avatar
    Join Date
    Jan 2003
    Posts
    501
    To quote the header file I got with gcc
    Quote Originally Posted by stdio.h
    /* Get a newline-terminated string from stdin, removing the newline.
    DO NOT USE THIS FUNCTION!! There is no limit on how much it will read.
    That is in reference to gets, always use fgets over gets.
    Help populate a c/c++ help irc channel
    server: irc://irc.efnet.net
    channel: #c

  11. #11
    & the hat of GPL slaying Thantos's Avatar
    Join Date
    Sep 2001
    Posts
    5,681
    gets() is the one thing I have no problem saying: NEVER EVER USE IT. THERE IS NO EXCUSE FOR USING gets().

  12. #12
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Even though it dosnt have built in array overrun you could always just code in an if statement to tell it the last chr is null if it exceeds size and then you wouldnt have to worry about \n being there
    Yeah, because you'd be too busy worrying about it crashing your program or causing a nice little security problem because someone used a buffer overrun to trash you OS or ...

    Quzah.
    Hope is the first step on the road to disappointment.

  13. #13
    Thanks everyone,

    I too agree there is no possible excuse to use gets() for any compilation. Why they created these functions, hence gets() and fflush(), still comes unclear to me.

    I like the method:
    Code:
    if( (c=strrchr( buf, '\n' )) )
        *c='\0';
    It's the fastest, safest, and most reasonable approach in my view to remove the '\n' character from the string.


    Once again thank you all, and thank you quzah,
    - Stack Overflow
    Segmentation Fault: I am an error in which a running program attempts to access memory not allocated to it and core dumps with a segmentation violation error. This is often caused by improper usage of pointers, attempts to access a non-existent or read-only physical memory address, re-use of memory if freed within the same scope, de-referencing a null pointer, or (in C) inadvertently using a non-pointer variable as a pointer.

  14. #14
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    fflush is a useful function, however, people always use it wrong around these parts, trying to flus input streams instead of output...

    Quzah.
    Hope is the first step on the road to disappointment.

  15. #15
    & the hat of GPL slaying Thantos's Avatar
    Join Date
    Sep 2001
    Posts
    5,681
    Well fflush() has its usages like flushing the output buffer. Most likely gets() was implamented before fgets(). Now the question is why the still allow it to live

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Function for removing character from a word
    By TheDeveloper in forum C Programming
    Replies: 6
    Last Post: 07-07-2009, 05:30 AM
  2. character set translation
    By password636 in forum C Programming
    Replies: 1
    Last Post: 06-08-2009, 11:45 AM
  3. Problem using sscanf fgets and overflow checking
    By jou00jou in forum C Programming
    Replies: 5
    Last Post: 02-18-2008, 06:42 AM
  4. Mac - Default Lines Endings - fgets() - no worky
    By Dino in forum C Programming
    Replies: 6
    Last Post: 01-30-2008, 11:59 PM
  5. mygets
    By Dave_Sinkula in forum C Programming
    Replies: 6
    Last Post: 03-23-2003, 07:23 PM