1
votes

I am currently following the K&R book on c programming and I have encountered a problem using the printf() function with an array. Everything the array is supposed to hold is correct as I have tested printing each element within the initial while loop, but when I try to print outside of the while loop and within the main() function I don't get the desired answer. Here is the code.

for(i=0;i<10;++i){
    ndigits[i]=0;
}
while((c=getchar())!=EOF){

    if(c>='0'&&c<='9'){
        ++ndigits[c-'0'];
    }
    else if(c==' '||c=='\t'||c=='\n'){
        ++nblank;
    }
    else{
        ++nother;
    }
}

for(i=0;i<10;++i){
    printf("%d ", ndigits[i]);
}
printf(" blank space: %d other: %d\n", nblank, nother); 

This program is supposed to count white space, other characters and store the number of occurrences of each digit in the array. Counting white space and other characters works fine when I have commented out the for loop for printing the array. However, when i run the program without commenting out printing the array it prints only the first element in the array, which is the number of zeros, with ^C next to it and the doesn't even reach the last line where the number white space and other characters are printed.

It is user input through keyboard btw and I am using notepad++ and MinGW as my compiler.

ex.

Input: 1353466113 udahkdakdjf
Output: 0 ^C

Input: 000000
Output: 6 ^C

I have tested my program with placing a printf() function within the while loop to check whether the array held the right values and it does. All help is much appreciated.

2
What are these things? ++ndigits[c-'0']; if(c>='0'&&c<='9'){Digital_Reality
Please post the entire code. Using just the part you posted, the code works just fine for me: 1353466113 udahkdakdjf -> 0 3 0 3 1 1 2 0 0 0 blank space: 2 other: 11 and 000000 -> 6 0 0 0 0 0 0 0 0 0 blank space: 1 other: 0. My complete code is here pastebin.com/yG7E95WFtwj
@Digital_Reality that code is incrementing the occurance of digits in array.Rahul
The above given code seems correct. If you are getting error please post the entire code.Rahul
are you allergic to the space key?Peter Miehle

2 Answers

1
votes
  1. Using Ctrl C to signal end of input does more than that, it signaleds program termination. Depending on your console, Ctrl D or Ctrl Z may do the trick.

  2. Insure ch is an int and not a char.

  3. Your test for white-space is good, but incomplete. Suggest

    #include <ctype.h>
    ...
    // else if(c==' '||c=='\t'||c=='\n'){
    else if (isspace(c)) {
    
0
votes

@user3191564 : I just tested out your code on my laptop and it gives me the same output as you put it. I think the EOF flag is what's giving you the weird output.

Everything else in the program looks to be right logically. Take a critical loop at that while loop, the getchar, and EOF.

And I don't know if you are using the getchar() quite rightly. For more info.