I'm new to C programming so if anything looks super wrong I'm sorry!
I need to make my array ( str[512] ) to be exactly 512 characters long after taking input from a text file with an unknown number of characters. After the text file input, there is supposed to be just lowercase 'x' until the 512 characters limit is reached. so if the text file is 'abcdf', my array needs to be 'abcdfxxxxxxxxxxxxxxxxxx(...)xxxxxxx' until there are 512 characters. When I run the program, it's a mess. First part of the code reads the text file, makes all the upper case letters lowercase, skips non alphabet characters and assigns the characters to the array. The second snippet is the problematic one that causes a messy output.
FILE * fp; char str[512]; int c, i = 0; fp = fopen("k1.txt", "r"); i = 0; while(!feof(fp)){ c = fgetc(fp); if (c == '\n') continue; c = tolower(c); if (c < 97 || c > 122) continue; str[i] = c; i++; for(i = 0; i < 512; ) { if (str[i] == '\0') str[i] = 'x'; i++; }
feof(fp)?i? Can you not start from the value at the end of thewhileloop, and then just set allcharsremaining in the array tox(keeping in mind the NUL termination)?if (str[i] == '\0')that is not going to work because you never actually fill instrwith such NUL characters that you are checking for. Instead,iis already at the end of the data that was read from file (after you fix thefeofproblem so you should start theforloop from that index and not 0.memset(str, 'x', sizeof str);and then to pass it as the buffer to fread at most the maximum size into like so:size_t len = fread(str, 1, sizeof str, stdin);. Nowlenis the number of bytes actually read, or0if the read failed or is short and you then check why. But be careful with the namestr, because if it's not NUL-terminated it's not a string.while( !feof(file) )always wrong?