read a line with getchar

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • kalar
    New Member
    • Aug 2007
    • 82

    read a line with getchar

    I want to read a line and put each word of this line in a linked list but i must use getchar.My problem is on how to read a line with getchar.(forget linked lists)
    i make this
    Code:
    #include <stdio.h>
    
    #define len 64
    
    int main(void){
        
        char str[len];
        int i;
        
          do{
             i=0;
             str[i]=getchar();
             i++;
             }while (str[i-1]!= '\n' && i<len);
             
         str[i-1]='\0';
    
         printf("%s", str); 
    
         return 0;
              }
    The problem the printf str doesn't print anything
  • tavianator
    New Member
    • Dec 2006
    • 38

    #2
    You set i=0 every time the loop executes. i never exceeds one. Then you set str[0] to '\0'. Set i=0 outside the loop.

    Comment

    • kalar
      New Member
      • Aug 2007
      • 82

      #3
      Ok. Now i want to seperate the words.
      example if i give:
      hello world

      I want to take hello and add it into the list and then for world do the same thing
      I thought something like this: in a for loop if i find any ' ' character i will replace it with \0. Will this work? or any other idea to do this?

      Comment

      Working...