string - calculate mean length of a line using C -
I have a text file in which I have filled one number rows with different text, with the length of a different line . The way I am using the Bend C + + command line tool BCC 32, I'm running on Windows 7 SP1. P> And then dynamically allocate memory by using malloc. And, you should calculate the line instead of 1, because when there is no '\ n' in the text file, there may still be a line if the text file contains a '\ n', then that means there are two rows (say, you are in line 1, and then you press 'et', which is '\ n', and then you reach the new line, So for one '\ n', there are 2 lines). Note- At present, your childcount contains Newlines ('\ n'), when it is printed. Finally, print the statement, because at the end of your program, you have already exited Newline by loop reducing the sum in the if statement of the second line.
What do I have to do, which calculates the average number of characters per line, which matters to me in my work, I wrote the following code in C to get it. Although I can not run the program after the program is compiled
Includes # lt; Stdio.h & gt; #to & lt include, stdlib.h & gt; #define LENGTH 10000000 int main () {char c; Int i; Int line_length; Int j; Int char_count; Char char_a [LENGTH]; Int line_a [LENGTH]; Int line_count; Long amount; Name avg_char_count; FILE * fp = fopen ("input.txt", "r"); If (! Fp) {fprintf (stderr, "can not open file"); Exit (1); } / * Read in file * / i = 0; Yoga = 0; While (char_a [i ++] = fgetc (fp)) sum ++; Printf ("Character Count:% d \ n", Yoga); / * Process array * / char_count = i; j = 0; Line_count = 0; While (J ++> & lt; char_count) {if (char_a [j] == '\ n') {sum--; Line_count ++; }} / * Calculation of average * / avg_char_count = sum / (float) line_count; Printf ("There is a # # relative # character in a line:% f \ n", avg_char_count); Return EXIT_SUCCESS; }
What's wrong with my code? Try declaring char_a and line_a as pointers for characters and int:
char * char_a; Int * line_a;
char_a = (four *) malloc (10000000 * size (four)); Line_a = (int *) malloc (10000000 * sizeof (int)); Second, when you reach the end of the file, your loop should end when the EOF is over.
while breaking (if char_a [i] = fgetc (fp)) {if (char_a [i ++] == eof); Yoga ++; }
/ * process array * / char_count = sum; j = 0; line_count = 1; While (J ++> & lt; char_count) {if (char_a [j] == '\ n') {sum--; line_count ++; }} <-
Comments
Post a Comment