help with getchar() and arrays

This is a discussion on help with getchar() and arrays within the C Programming forums, part of the General Programming Boards category; can someone please tell me why this piece of code does not work properly?...im trying to get input using getchar ...

  1. #1
    Registered User
    Join Date
    Apr 2006
    Posts
    7

    help with getchar() and arrays

    can someone please tell me why this piece of code does not work properly?...im trying to get input using getchar and put it into an array. then, print the contents of the array.

    Code:
    #include <stdio.h>
    #include <ctype.h>
    #define ARRAY_SIZE 1000
    
    int main(int argc, char **argv) {
    
        int input;
        char Description[ARRAY_SIZE];
        int counter = 0;
        while((input = getchar()) != EOF) {
    
            Description[counter] = input;
            counter++;
            input = getchar();
        }
    
        printf("%s",Description);
    
        return 0;
    
    }

  2. #2
    Registered User Mortissus's Avatar
    Join Date
    Dec 2004
    Location
    Brazil, Porto Alegre
    Posts
    152
    You are using getchar twice!

  3. #3
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,047
    Get rid of this line, otherwise you'll only read every other character:
    Code:
    input = getchar();
    And you might want to change this:
    Code:
    while((input = getchar()) != EOF) {
    to
    Code:
    while((input = getchar()) != EOF && input != '\n') {
    to only read one line.
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. how to merge two arrays recursevly..
    By transgalactic2 in forum C Programming
    Replies: 117
    Last Post: 01-11-2009, 03:47 PM
  2. Newb Help: Full Arrays and Functions
    By LycanGalen in forum C Programming
    Replies: 5
    Last Post: 01-31-2008, 07:35 PM
  3. Trying to understand Arrays
    By LaGood in forum C Programming
    Replies: 5
    Last Post: 08-16-2007, 10:07 PM
  4. Pointers to Multidimensional Arrays
    By kidburla in forum C Programming
    Replies: 10
    Last Post: 10-29-2005, 10:45 PM
  5. Help with arrays again
    By viclaster in forum C Programming
    Replies: 7
    Last Post: 10-08-2003, 09:44 AM

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