Thread: reading line by line - input function

  1. #1
    Registered User
    Join Date
    Feb 2011
    Posts
    3

    reading line by line - input function

    Hello, new here and hoped someone could assist me.

    The description for the task was:
    returns 1 if a word is successfully read & stored in the array word of n characters; otherwise returns 0 on end of file or when the user inputs the word eof

    I think I am close but it doesn't quite work so I was hoping someone could point out what's going wrong, because I am not seeing it!

    The problems I am having are:
    - when I try to enter the eof (byebyenow in this case) the program tells me it is too long, and doesn't exit.
    - a word with <= 4 characters will cause a "STATUS_ACCESS_VIOLATION" error and it creates a stackdumpfile
    - 5 or 6 characters is also apparently too long

    Thanks for helping!

    Code:
    #include <stdio.h>
    #include <string.h>
    #define BUFSIZE 32
      
    int get_word(const char prompt[], char word[], size_t n, const char eof[]);
    
    int get_word(const char prompt[], char word[], size_t n, const char eof[])
    {	
    	char line[BUFSIZE];
    	while(1){
    		printf("%s\n", prompt);
    		if(fgets(line, BUFSIZE, stdin) != NULL)
    		{
    			if(strcmp(line, eof) == 0)
    			{
    				printf("Program over.");
    				return 0;
    			}
    			if(strlen(line) < n)
    			{
    				strcpy(word, line);
    				printf("%s was 6 or less chars. Thankyou\n", line);
    				return 1;
    			}else{
    				printf("%s was too long! Try again.\n", line);
    			}
    		}
    	}
    }
    
    int main(void)
    {
    	char input[6];
    	if(get_word("Enter a word with 6 chars or less, or BYEBYENOW to quit.", input[6], 6, "BYEBYENOW") == 1)
    	{
    		printf("%s\n", input);
    	}
    	return 0;
    }

  2. #2
    Registered User
    Join Date
    May 2010
    Location
    Naypyidaw
    Posts
    1,314
    man page fgets section 3

    Reading stops when a newline character is found, at end-of-file or error.
    The newline, if any, is retained. If any characters are read and there
    is no error, a `\0' character is appended to end the string.
    Strip new line.

  3. #3
    Registered User
    Join Date
    Aug 2010
    Location
    Rochester, NY
    Posts
    196
    Quote Originally Posted by Lindira-123 View Post
    Hello, new here and hoped someone could assist me.

    The description for the task was:
    returns 1 if a word is successfully read & stored in the array word of n characters; otherwise returns 0 on end of file or when the user inputs the word eof

    I think I am close but it doesn't quite work so I was hoping someone could point out what's going wrong, because I am not seeing it!

    The problems I am having are:
    - when I try to enter the eof (byebyenow in this case) the program tells me it is too long, and doesn't exit.
    - a word with <= 4 characters will cause a "STATUS_ACCESS_VIOLATION" error and it creates a stackdumpfile
    - 5 or 6 characters is also apparently too long

    Thanks for helping!

    Code:
    #include <stdio.h>
    #include <string.h>
    #define BUFSIZE 32
      
    int get_word(const char prompt[], char word[], size_t n, const char eof[]);
    
    int get_word(const char prompt[], char word[], size_t n, const char eof[])
    {    
        char line[BUFSIZE];
        while(1){
            printf("%s\n", prompt);
            if(fgets(line, BUFSIZE, stdin) != NULL)
            {
                if(strcmp(line, eof) == 0)
                {
                    printf("Program over.");
                    return 0;
                }
                if(strlen(line) < <= n)
                {
                    strcpy(word, line);
                    printf("%s was 6 or less chars. Thankyou\n", line);
                    return 1;
                }else{
                    printf("%s was too long! Try again.\n", line);
                }
            }
        }
    }
    
    int main(void)
    {
        char input[6];
        if(get_word("Enter a word with 6 chars or less, or BYEBYENOW to quit.", input[6] input, 6, "BYEBYENOW") == 1)
        {
            printf("%s\n", input);
        }
        return 0;
    }
    Issues are marked in Blue, corrections in Green.

    That is passing the 7th index of the input array. The array is 6 indices long.

    It's
    A) Out of the bounds of the array
    B) Only passing the one byte (character), the 7th.
    C) You should allocate 7 (ie. char input[7]), as you need room for the trailing NULL byte.

    If you
    A) Modify the function call to simply be "input' as the second argument (passing the address of the array)
    B) Modify the second if statement to read less than or equal to (<=), not just less than. Then it works fine.

    Now, you'll notice it only works as it should, but possibly not as expected, because if you type a 6 letter word, it'll say it's too long, it'll only accept words up to 5 letters. Why?

    Well because when you type a 5 letter word, ie., hello, then hit enter, you get the following characters:
    'h', 'e', 'l', 'l', 'o', '\n'

    The '\n' at the end is the newline character. It happened because you hit enter.

    If you type a 6 letter word then hit control + D (end of input), it'll work.
    Last edited by Syndacate; 02-06-2011 at 12:57 AM.

  4. #4
    Registered User
    Join Date
    Aug 2010
    Location
    Rochester, NY
    Posts
    196
    Quote Originally Posted by Lindira-123 View Post
    The problems I am having are:
    - when I try to enter the eof (byebyenow in this case) the program tells me it is too long, and doesn't exit.
    See below for explanation, when you type that, you're getting that + the newline character., ie. 'B', 'Y', 'E', 'B', 'Y', 'E', 'N', 'O', 'W', '\n', which isn't equal to "BYEBYENOW".

    Quote Originally Posted by Lindira-123 View Post
    - a word with <= 4 characters will cause a "STATUS_ACCESS_VIOLATION" error and it creates a stackdumpfile
    The access violation occurs because you're passing the character (index 7) of a memory you don't own. You don't own it because you didn't allocate it. This creates undefined behavior.

    Indices are 0 based. That means if you allocate 6, the largest you can go is index 5. You don't want to pass just one character/byte up there, you need to pass the address of the allocated array...so leave off the subscript.

    Quote Originally Posted by Lindira-123 View Post
    - 5 or 6 characters is also apparently too long
    What appears to be a 4 character string, is actually 5 characters, the last being the newline character. It's not 6 because you used less than n, not less than or equal to n, so since n is 6, a string length of 5 is the largest you can have.

  5. #5
    Registered User
    Join Date
    Feb 2011
    Posts
    3
    Thanks for the help, but still one issue...

    The loop won't....loop?
    If I enter a word with <= 6 characters, it just ends.
    Last edited by Lindira-123; 02-06-2011 at 01:08 AM. Reason: fixed one problem

  6. #6
    Registered User
    Join Date
    Aug 2010
    Location
    Rochester, NY
    Posts
    196
    Quote Originally Posted by Lindira-123 View Post
    Thanks for the help, but still one issue...

    The loop won't....loop?
    If I enter a word with <= 6 characters, it just ends.
    That's because you have a return statement in there. The keyword 'return' - returns from the function. If the function happens to be main, it exits the program.

    EDIT:
    That's why the program doesn't print the string when you exit. Because you return 0, that exits the function, and returns 0, since 0 != 1, the if statement evaluate to false, which is why nothing gets printed. Return exits the function and returns to the caller, it's not synonymous with "ending the program."

    If you want to end the program with the status code, you can do something like this:
    Code:
    int return_value = get_word("Enter a word with 6 chars or less, or BYEBYENOW to quit.", input, 6, "BYEBYENOW");
    
    if (return_value == 1) // (Can also just do "if (return_value)" as in C, 0 is false, anything else is true (in a boolean expression).
    {
        printf("%s\n", word);
    }
    
    return return_value;
    Since the return in red is in your main function, it will exit the program, and the program will exit with the status code: 1
    Last edited by Syndacate; 02-06-2011 at 01:20 AM.

  7. #7
    Registered User
    Join Date
    Feb 2011
    Posts
    3
    Yep I just found that, and realised I don't think it needs to loop once the user enters the right amount of chars.

    Thanks for the help

  8. #8
    Registered User
    Join Date
    Aug 2010
    Location
    Rochester, NY
    Posts
    196
    Quote Originally Posted by Lindira-123 View Post
    Yep I just found that, and realised I don't think it needs to loop once the user enters the right amount of chars.

    Thanks for the help
    Probably not, regardless, if this is for a school assignment (which it sounds like it is), please state that in the original post. This way people know exactly how much help to give you.

    People on forums shouldn't do the work for you, but contrary to popular belief, IMO, there's no harm in helping to point somebody in the right direction, point out flaws, etc.

    Teachers tend to flip ........ on the 'academic dishonesty' coin when people help other people. As sick as it is, that's why I never give credit in my work to anybody that helps me, as a teacher now has potential to scream 'academic dishonesty' bloody murder. While you need to learn for yourself, there's no harm in helping others, especially if you're not "giving them" the solution without them honestly trying.

    I chose to help you even though this sounds like homework as it seems like you made a serious effort at programming the thing, and you took the debugging effort to figure out exactly what was the issue, not just "sometimes it's doing this, and sometimes it's doing that" - you actually took the time to debug it and find that <= 4 characters was where the issue was. Debugging like that, is key.

    Just some food for thought.

    Helping people for school and academic dishonesty is a very fine line, please make sure people you're helping know that it exists.

  9. #9
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by Syndacate
    As sick as it is, that's why I never give credit in my work to anybody that helps me, as a teacher now has potential to scream 'academic dishonesty' bloody murder.
    Ironically, failure to give credit where it is due is academic dishonesty, whereas proper citation when you also actually did critical work is acceptable.
    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

  10. #10
    Registered User
    Join Date
    Aug 2010
    Location
    Rochester, NY
    Posts
    196
    Quote Originally Posted by laserlight View Post
    Ironically, failure to give credit where it is due is academic dishonesty, whereas proper citation when you also actually did critical work is acceptable.
    No, it's academic ignorance more than dishonesty.

    I can say it as I've been (and am) a student, it's one of those things like socialism, it's great in theory, fails IRL.

    Why does it fail?

    Well it's quite simple. If you blatantly ignore the fact that that somebody pointed out that it should be a less than sign rather than a less than or equal sign, you made a stupid logic error, it's nothing "you didn't know" - I'm pretty sure everybody gets the idea quite well, it's simply somebody pointed it out. If you ignore it, you still did the work (at least in my opinion), it's not academic dishonesty, it's your own work. Somebody just gave you an idea to entertain as to what's probably screwing it up. I see no issue with that.

    On the flipside, if you give written credit (ie. somebody told me this was an issue), you'll find yourself called into a professor's office, and interrogated as to the academic honesty (or lack there of?) of your work like a ........ing McCarthy trial. Then, the professor has "PROOF" - you "admitted it" - that if they deem so, can say you "cheated." Now you're on all defense, why? Because you came forward from the start.

    If I get an idea, or take code/algorithm from an 'open' source, bringing REAL academic issues to question, I most certainly mention them, that gives the original author's credit.

    But if you've seen what I've seen, which is professors jumping down peoples' throats because they mentioned where they got sources from, you get a pretty sour taste in your mouth about mentioning the fact that somebody helped you find a NULL pointer. The sick part is there's a thin line between academic dishonesty, and just helping somebody, the professor chooses that line. He gives the grade.

    I'm not telling the OP what's right, I'm simply stating my views on it. If I didn't believe in academic dishonesty I wouldn't have mentioned it. I just believe it's so wishy-washy amongst professors that it's not worth mentioning if you know it's not academically dishonest. Taking code and calling it your own is academically dishonest, getting a bit of help isn't. Then again, maybe it is, as all these lines are arbitrary.

    It's a complex subject with lots of gray area, but in the end, I believe a student has the right to get help, as long as the help doesn't entail somebody doing the work for him. You don't have to list help from the student help center, but you do from somebody else...but the student help center is just students...so does that mean you don't have to list somebody if they're on duty, but you do if they're not? I just prefer not to be on defense for something I know wasn't dishonest.

    Blatantly speaking, the whole subject just sucks, but is necessary. I just encourage people asking homework like questions to notify people helping that it's for an assignment, to help prevent academic dishonesty. Though I don't believe people should be put on trial just because they wanted to be straight forward...but sometimes they are, and that's BS, IMO.

    This forum exists to help people with C/C++/C#. Why should that right only be available if you're not a student? (and the rebuttal "You can get help if you're a student, as long as you cite it" is useless, IMO, as it "admits that work is not your own", so to speak).

    EDIT:
    On a side note. These useless professors seem to be one of two categories.
    A) Teach introductory courses and don't know any of the upper level courses (ie. you're smarter than them by the time you graduate)
    B) These research oriented jack-off professors who don't know/care anything about teaching - just their research

    Once you get into the higher level courses, good teachers are aware that people need help, and are OK with the idea of people helping one another, as long as it's not 'cheating.' But at that level, everybody knows what cheating is, so the line isn't as gray anymore.. I've had really good (real teachers, not researchers) professors in the upper level courses who actively SEE people discussing ideas for projects, and know that these people understand what academic dishonesty is, realize the class is hard, and realize there's more help than harm in students discussing ideas/approaches to solutions with one another.

    If you don't get what I'm saying, it's pointless to try and ask further. It's simply something you come to understand from spending a decent time in an educational environment.

    EDIT #2:
    In short, what I'm saying is:
    IMO: What's "acceptable" isn't always honest, and what's not acceptable isn't always dishonest.
    Last edited by Syndacate; 02-06-2011 at 02:53 AM.

  11. #11
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by Syndacate
    No, it's academic ignorance more than dishonesty.
    What is "it"?

    Quote Originally Posted by Syndacate
    If you don't get what I'm saying, it's pointless to try and ask further. It's simply something you come to understand from spending a decent time in an educational environment.
    I think you completely missed the word "ironically" in my statement
    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
    Registered User
    Join Date
    Aug 2010
    Location
    Rochester, NY
    Posts
    196
    Quote Originally Posted by laserlight View Post
    What is "it"?
    "it" is "failure to give credit where it's 'due'."

    Quote Originally Posted by laserlight View Post
    I think you completely missed the word "ironically" in my statement
    Yeah, I saw that, I just wanted to clarify, I don't support academic dishonesty, but being completely "honest" can land you in such a world of ........ . It's pretty crappy.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. In over my head
    By Shelnutt2 in forum C Programming
    Replies: 1
    Last Post: 07-08-2008, 06:54 PM
  2. Undefined Reference Compiling Error
    By AlakaAlaki in forum C++ Programming
    Replies: 1
    Last Post: 06-27-2008, 11:45 AM
  3. dllimport function not allowed
    By steve1_rm in forum C++ Programming
    Replies: 5
    Last Post: 03-11-2008, 03:33 AM
  4. Custom Made Safe Input Function
    By Beast() in forum C Programming
    Replies: 6
    Last Post: 08-21-2004, 10:19 PM
  5. Interface Question
    By smog890 in forum C Programming
    Replies: 11
    Last Post: 06-03-2002, 05:06 PM