Friday, May 21, 2010

Why Doesn't My C Source Code Work?

#include %26lt;stdio.h%26gt;


#include %26lt;string.h%26gt;





int main(void) {


//user information


printf("This programme counts the number of each letter in passage.txt.");





//define file and arrays.


FILE *FileReference;


char Letter[2]= {0}, ArrayOfLetters[128]= {0};


int i=65;





//open file


FileReference=fopen("passage.txt", "r");


if (FileReference == NULL) {


printf("File did not open correctly\n");


return 1;


}





//Loop for capital letters


for (i=65; i%26lt;=90; i++) {


while (fgets(Letter,2,stdin) !=0) {


ArrayOfLetters[(Letter[2])]++;


}


}





printf("\n\n%d=%s", ArrayOfLetters, ArrayOfLetters);


return 0;


}

Why Doesn't My C Source Code Work?
FileReference=fopen("passage.t... "r");





should be





FileReference=fopen("passage.txt" , "r");





fopen takes two arguments.
Reply:Try this - at least it works via my old Watcom compiler








#include %26lt;stdio.h%26gt;


#include %26lt;string.h%26gt;


#include %26lt;conio.h%26gt;





int main(void)


{


//user information


printf("This programme counts the number of each letter in passage.txt.\n\n");





//define file and arrays.


FILE *FileReference;


int LetterCount[26];


int i;


int c;





for (i=0; i%26lt;26; i++)


{


LetterCount[i] = 0;


}





//open file


FileReference=freopen("passage.txt", "r", stdin);


if (FileReference == NULL)


{


printf("File did not open correctly\n");


printf("Press any key\n\n");


getch(); // So window does not disappear via Windows


return 1;


}





while( (c = getchar()) != EOF )


{


//Loop for capital letters


for (i=65; i%26lt;=90; i++)


{


if (i == c) LetterCount[i - 65]++;


}


}


fclose (FileReference);





for (i=0; i%26lt;26; i++)


{


printf (" %c %d\n", i + 65, LetterCount[i]);


}


printf("\nPress any key\n");


getch(); // So window does not disappear via Windows


return 0;


}
Reply:FileReference=fopen("passage.t... "r");


Shouldn't that be FileReference=fopen("passage.txt", "r");





There is an easier way to do this: If you are expecting ascii then you can create an array of 256 elements of int then get the acsii code of each char in the file and increment the element at the position in the array that matches the ascii code of the char.


I'm not a C programmer but the concept should work.
Reply:you need to clear your ArrayOfLetters[128] array. you are setting the last to 0 (string terminator) which is fine, but every other position has garbage in it. at the beginning of your program, add


for (int a = 0; a %26lt; 128; a++)


ArrayOfLetters[a] = 0;
Reply:Presumably you know at what point it stops working, and what error code is being returned to you. Care to share?
Reply:please reiterate on exactly what compilation errors you are getting if any.


No comments:

Post a Comment