Input

This is a discussion on Input within the C Programming forums, part of the General Programming Boards category; Hi I am trying a thing. in that i want to get lines of text which has special chars,numbers and ...

  1. #1
    Registered User
    Join Date
    Jan 2008
    Posts
    8

    Input

    Hi
    I am trying a thing. in that i want to get lines of text which has special chars,numbers and chars and i dont want to allocate memory at the beginning. i want to allocate memory exactly needed for the input given.i dont want to waste memory.

  2. #2
    Jack of many languages Dino's Avatar
    Join Date
    Nov 2007
    Location
    Katy, Texas
    Posts
    2,309
    OK, so do it.

  3. #3
    Registered User
    Join Date
    Jan 2008
    Posts
    58
    i dont want to waste memory.
    You can do it but it wastes time by only allocating the memory needed. That's a lot of calls to realloc.
    Code:
    char *getline(void)
    {
        char *s = NULL;
        int n = 0;
        int ch;
    
        do
        {
            ch = getchar();
            s = (char*)realloc(s, n + 2);
            s[n++] = ch;
        }
        while ( ch != '\n' );
    
        s[n] = '\0';
    
        return s;
    }
    If you want it to be fast you have to waste memory somewhere. Something like an array that holds parts of the string so you can use fread or fgets and call realloc less often.

  4. #4
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,452
    Use a temp buffer (typically BUFSIZ in size) to read a line.
    Measure it's length, then allocate that much space, copy the line and save for later.
    Repeat until done.
    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.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Problem grabbing k/b input
    By falcon9 in forum C Programming
    Replies: 2
    Last Post: 10-28-2007, 11:47 AM
  2. continues input
    By Matty_Alan in forum C Programming
    Replies: 2
    Last Post: 06-22-2007, 10:04 PM
  3. Input statement problem
    By une in forum C Programming
    Replies: 3
    Last Post: 05-29-2007, 11:16 PM
  4. For loop problems, input please.
    By xIcyx in forum C Programming
    Replies: 2
    Last Post: 04-22-2007, 03:54 AM
  5. Simple Console Input for Beginners
    By jlou in forum C++ Programming
    Replies: 0
    Last Post: 06-21-2005, 01:50 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21