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.
1353466113 udahkdakdjf
->0 3 0 3 1 1 2 0 0 0 blank space: 2 other: 11
and000000
->6 0 0 0 0 0 0 0 0 0 blank space: 1 other: 0
. My complete code is here pastebin.com/yG7E95WF – twj