Why does printf not print after a while or for loop in C?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Quidnunc
    New Member
    • Jul 2012
    • 3

    Why does printf not print after a while or for loop in C?

    First, I am completely new and learning on my own. I would like the following code to print: "Why doesn't this print?" and "I would like to print the sum of nc: 5". What am I doing wrong.

    Code:
    #include <stdio.h>
    
    //Use to test ideas and formats//
    
    main()
    {
    	int c, nc;	
    	
    	nc = 0;
    	
     	printf ("This prints.\n");
    	while ((c = getchar()) != EOF)
    	{
    		++nc;
    		putchar(c);
    		printf("%d,", nc);
    	   	
    	}
    	printf ("Why doesn't this print?");
    	printf ("I would like to print the sum of nc: %d", nc);
    }
    My result as compiled by gcc -o testing testing.c


    This prints.
    test
    t1,e2,s3,t4,
    5,

    As you can imagine, I have not figured out how to sum and print as the above code indicates, which complicates my ability to do many of the exercises in "The C Programming Language". I am using a MacBook gcc compiler and X code as well. I cannot get the last two printf functions to work. As mentioned, I am new to programming. I believe it is because the program is not exiting the loop. I did the temperature example with "while (fahr <= upper)" and the printf printed.
  • divideby0
    New Member
    • May 2012
    • 131

    #2
    I don't use a Mac, so I don't know what its behavior is, but you might try

    Code:
    while((c = getchar()) != '\n' && c != EOF) {
       ...
    }
    
    printf("...");
    printf("...");
    fflush(stdout);  // force the output buffer
    
    while(getchar() != '\n'){} // wait for a newline
    EOF may signal the program to terminate. If there's a window displaying your output, it may be that it's closing before you have a chance to view it.

    Comment

    • weaknessforcats
      Recognized Expert Expert
      • Mar 2007
      • 9214

      #3
      You need to tell your program that all of the input has been received. Otherwise, your loop runs forever fetching new input.

      The end-of-all-input is CTRL+Z.

      Comment

      • Quidnunc
        New Member
        • Jul 2012
        • 3

        #4
        Divideby0:

        First, I appreciate the fact that my two lines print (by the way, I forgot the \n ) :). Sadly, I can only run the program once now and I would like it to loop until I want to exit. Still, your suggestion worked once for the Terminal gcc and Xcode.

        Second, I have a newbie gripe! Why do I have to put so much extra code into the "The C Programming Language Book" examples to get their programs to work? Although I believe I know the answer, I wonder if the program worked during the printing of the book? Did a standard change or something?

        I suspect I will be using this site often as I learn since I am a complete loner now. I hope to see more of your responses! I plan to use it like a study group.

        With that said, I would like to share something personal as well. I have combat PTSD, Gulf War Syndrome, major depression, and a brain disease that has side-lined me from chemical engineering and brain death is suspected. Sadly, psychological testing has shown that my IQ and abstract thinking have declined. When I tell you what I have you are statistically likely to look at me differently. In addition to the previously mentioned and a few more, I have been diagnosed with late onset schizophrenia that is chronic now. I am forced to file for disability. During my experiences, I have met a few schizophrenics that program. As such, I am trying to learn for a bit of fun and because I hope to get enough knowledge to maybe earn a little money. If nothing else, I can provide free tutoring to a low-income high school kid that has engineering aspirations.

        I share the above because I suspect I will now struggle more than the past. It is frustrating. I wish the book code was a bit more correct. I realize authors will create errors but the errors usually correlate to the content prior to the exercises or examples.

        weaknessforcats :

        I tried yours and could not get it to work. I did learn how to clear the terminal window though :). I hope to see your help in the future as well.

        Both:

        Any other suggestions will be appreciated. I will play around with the code and try to get it to work until I close out.
        Last edited by Quidnunc; Jul 1 '12, 07:05 PM. Reason: I wanted to combine comments!

        Comment

        • weaknessforcats
          Recognized Expert Expert
          • Mar 2007
          • 9214

          #5
          The examples in the C Programming Language book are not intended to teach you C.

          Therefore, many of the items you need to make running program are omitted. However, the web has thousands of sites with thousands of examples so the omission in the book is really not so serious.

          You have to read that book like a legal contract. There are no extra words. No handy explanations as to why. Every period and comma has significance. The author wrote that C is a tiny language and therefore needs only a tiny book.

          Maybe so. However, I learned C by reading various textbooks bu even these had examples that just illustrated a particular point. So maybe all the #includes were omitted and possibly even main().

          As to looping your progrsm until you wish to exit just designate your exit character and test for it inside the loop. When you find it use a break statement to exit the loop.

          Comment

          • divideby0
            New Member
            • May 2012
            • 131

            #6
            I am in the process of learning C on my own as well; from my experience, books tend to gloss over core language features and use simple code snippits. Forums are a nice compliment though and weaknessforcats is very helpful.

            My version of the loop terminated as soon as it encountered a new line '\n'. What you might try is keeping your version of the loop body, and add the extra stuff after the loop exits.

            You can also wait on a specified character to exit your loop. For example, something like below is similar to using getchar, but quits on encountering a 'Q' or if scanf fails.

            Code:
            char c;
            int cn = 0;
            
            while((scanf(" %c", &c)) == 1 && c != 'Q') {
               ...
            }
            the char type is used for "c" instead of an int to avoid a stream error in scanf. that way you can enter digits, characters, or punctuation.

            Comment

            • Banfa
              Recognized Expert Expert
              • Feb 2006
              • 9067

              #7
              The main point is that stdin never returns EOF because the end of the file is never reached, the stream is continuous. You will need to work out another way and indicating that the end of the data has been reached. Commonly a sentinel value is used, that is a specific input value that means end input, examples common used are 'q', 'x', -1 or just a blank line.

              Comment

              • Quidnunc
                New Member
                • Jul 2012
                • 3

                #8
                Thanks for all the excellent information.

                Comment

                Working...