Thread: How do i make my readline function accept empty input?

  1. #1
    Registered User
    Join Date
    Oct 2020
    Posts
    18

    How do i make my readline function accept empty input?

    Hi all, title. Basically this is my readline

    Code:
    int read_line(char str[], int n){
      int ch, i = 0;
    
    
      while (isspace(ch = getchar()))
        ;
      while (ch != '\n' && ch != EOF) {
        if (i < n)
          str[i++] = ch;
        ch = getchar();
      }
      str[i] = '\0';
      return i;
    }
    and this is my main code
    Code:
    printf("Enter word: ");        read_line(word_str,MAX_LEN);
            if (word_str[0] == '\0')
                break;
    I need to trigger the break when the user makes an empty input. E.g. after entering a word, when program prints "Enter word" again the user just hits enter. But currently for my program what happens is that enter just goes to the next line until i actually input a character/string. Thank you all for the help.

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,675
    > while (isspace(ch = getchar()))
    > ;
    > while (ch != '\n' && ch != EOF) {
    The problem is that isspace('\n') is true, so you're not getting out of the first loop by typing a blank line.
    isspace - C++ Reference
    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 2020
    Posts
    18

    Thank yoU!

    Quote Originally Posted by Salem View Post
    > while (isspace(ch = getchar()))
    > ;
    > while (ch != '\n' && ch != EOF) {
    The problem is that isspace('\n') is true, so you're not getting out of the first loop by typing a blank line.
    isspace - C++ Reference

    Thank you for the help sir! Fixed ))

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. readline() function from UNP book and syncterm
    By cnnx in forum C Programming
    Replies: 3
    Last Post: 01-15-2015, 12:41 PM
  2. How to divide readline() input strings?
    By gamers18 in forum C Programming
    Replies: 4
    Last Post: 12-03-2012, 11:11 AM
  3. Cannot open include file: 'readline/readline.h'
    By arupsarkar in forum C++ Programming
    Replies: 2
    Last Post: 06-25-2010, 11:07 AM
  4. Replies: 17
    Last Post: 10-22-2007, 04:58 PM
  5. Make accept() stop
    By b00l34n in forum Networking/Device Communication
    Replies: 28
    Last Post: 12-20-2004, 06:50 PM

Tags for this Thread