简体   繁体   中英

Printing One Dimensional Array with For Loop Programming C

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.

  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)) { 

@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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM