C For cycle execution

I have a simple program (based on example from The C programming language ed. 2 section 1.5.2 book) for characters counting. The program itself is very simple, however I am no getting the expecting results.

It seems that numberOfChars is incremented twice and I do not not why...?

I am using cygwin + gcc compiler, please see the image: C For cycle execution

int main () {        int numberOfChars;        for(numberOfChars = 0; getchar() != EOF; numberOfChars++)          ;   //null statement      printf("Number of chars = %d\n", numberOfChars);      return 0; } 

Thanks for any help :-)

Replay

To get a 3, you can write:

#include <stdio.h>

int main () {
        int numberOfChars = 0;

        do {
                while(getchar() != '\n')
                        numberOfChars++;
        } while(getchar() != EOF && numberOfChars++);

        printf("Number of chars = %d\n", numberOfChars);

        return 0;
}

Then press Ctrl + D to exit the nested loop.

In fact, your program is correct. It gave you 6 because you've entered 6 characters: 1, \n, 2, \n, 3, \n.

Create a file, then run the cygwin od program, followed by a run of the example C program :

od -x < testfile
a.out < testfile

Then you can see what & how many characters you had exactly in the file and avoid surprises.

As a debugging aid, if I suspected something was wrong, I'd add something like :

int c; for(numberOfChars = 0; (c = getchar()) != EOF; numberOfChars++)
    printf( "\0x%x", c);

To understand the processing my code was doing.

Category: c# Time: 2016-02-07 Views: 0
Tags:

Related post

iOS development

Android development

Python development

JAVA development

Development language

PHP development

Ruby development

search

Front-end development

Database

development tools

Open Platform

Javascript development

.NET development

cloud computing

server

Copyright (C) avrocks.com, All Rights Reserved.

processed in 0.203 (s). 12 q(s)