Thread: Problem with for

  1. #1
    Registered User
    Join Date
    Jan 2016
    Posts
    4

    Problem with for

    Hi guys, need another time your help..

    At the moment i have to write a program what is dealing with the stack memory.. but that does not really matter, i actually have a mistake with my for loop..

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    
    struct TStack
      {
      char Daten[100];
      struct TStack *Next;
      };
    
    
    struct TStack *Keller = NULL;
    
    
    void Push(char *Daten)
      {
      struct TStack *Element;
    
    
      Element = (struct TStack *) malloc(sizeof(struct TStack));
      strcpy(Element->Daten, Daten);
      Element->Next = Keller;
      Keller = Element;
      }
    
    
    void Pop(char *Resultat)
      {
      struct TStack *Element;
    
    
      if (Keller == NULL)
        printf("Der Keller ist leer!\n");
      else
        {
        strcpy(Resultat, Keller->Daten);
        Element = Keller;
        Keller = Keller->Next;
        free(Element);
        }
      }
    
    
    int main(void)  {
      char str[100];
      int n, i;
      char satz[30];
    
    
      printf("\nWie viel Zeichensaetze wollen Sie eingeben?");
      scanf("%i",&n);
    
    
      for(i=0; i<n; i++)
        {
        printf("\nGeben Sie ihren %i.Zeichensatz ein: ",(i+1));
        fgets(satz, 30, stdin);
        Push(satz);
        }
    
    
      while (Keller != NULL)
        {
        Pop(str);
        printf("%s\n",str);
        }
    
    
      return(0);
      }

    The mistak is, that the for loop, always skips the first step. Hope you understand my english und furthermore you can help me..

    much greetings

  2. #2
    Registered User
    Join Date
    Jun 2011
    Posts
    4,509
    Code:
    scanf("%i",&n);
    After you enter a value (and press enter), a newline is left in the buffer.

    Code:
    fgets(satz, 30, stdin);
    The first time you enter the "for()" loop, this "fgets()" reads the newline that was left in the buffer.

    See here for more information: FAQ > How do I avoid a "dangling" newline when reading single character user input? - Cprogramming.com

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 3
    Last Post: 02-09-2014, 06:46 PM
  2. Problem passing argument into function, basic problem
    By tsdad in forum C++ Programming
    Replies: 7
    Last Post: 05-22-2013, 12:09 PM
  3. Replies: 2
    Last Post: 01-06-2013, 07:49 AM
  4. Replies: 1
    Last Post: 12-07-2012, 10:00 AM
  5. Replies: 4
    Last Post: 10-16-2008, 07:30 PM

Tags for this Thread