This discussion has been locked.
You can no longer post new replies to this discussion. If you have a question you can start a new discussion

How to let gets() work correctly?

IN C Starndard lib, use gets can input string form stdio.

for example, push [backspace] can remove the last char.

But when i use gets(), it keep backspace char (0x0B).

Parents
  • Any reason why you missed the instruction how to post source code? Notice any difference in readability?

    char *getstring(char *string) {
        char *pointer;
        INT ch;
    
        pointer = string;
        while (1) {
            ch = _getchar_lk();
            if (ch == EOF) {
                return NULL;
            }
    
            if (ch == 8) {
                if (pointer > string) {
                    putchar('\b');
                    putchar(' ');
                    putchar('\b');
                    pointer--;
                }
            } else if (ch == '\r' || ch =='\n' || ch >= ' ') {
                putchar(ch);
                if (ch == '\r') putchar('\n');
                if (ch == '\n' || ch == '\r') break;
                *pointer++ = ch;
            }
        }
    
        *pointer = 0;
        return string;
    }
    


    By the way - what happens if you have already received characters that you have stored in your string when you get an EOF?

    Another thing - exactly how large is your string? What happens if someone enters moer characters than what will fit in string?

Reply
  • Any reason why you missed the instruction how to post source code? Notice any difference in readability?

    char *getstring(char *string) {
        char *pointer;
        INT ch;
    
        pointer = string;
        while (1) {
            ch = _getchar_lk();
            if (ch == EOF) {
                return NULL;
            }
    
            if (ch == 8) {
                if (pointer > string) {
                    putchar('\b');
                    putchar(' ');
                    putchar('\b');
                    pointer--;
                }
            } else if (ch == '\r' || ch =='\n' || ch >= ' ') {
                putchar(ch);
                if (ch == '\r') putchar('\n');
                if (ch == '\n' || ch == '\r') break;
                *pointer++ = ch;
            }
        }
    
        *pointer = 0;
        return string;
    }
    


    By the way - what happens if you have already received characters that you have stored in your string when you get an EOF?

    Another thing - exactly how large is your string? What happens if someone enters moer characters than what will fit in string?

Children
No data