Home > Software engineering >  Filling the \0 spaces of an array with 'x'
Filling the \0 spaces of an array with 'x'

Time:06-21

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  ;    }

CodePudding user response:

The condition of the while loop is incorrect

while(!feof(fp)){

At least you need to check that i is less than 512

Also this for loop

for(i = 0; i < 512;  ) {
    if (str[i] == '\0') str[i] = 'x';
    i  ;    }

does not make a sense because the array after the preceding while loop will not contain the zero character '\0'.

You should write something like the following

int c;
size_t i = 0;
 
while (  i < 512 && ( c = fgetc( fp ) ) != EOF )
{
    if ( isalpha( c ) )
    {
        str[i  ] = tolower( c );
    }
}

while ( i < 512 ) str[i  ] = 'x';

CodePudding user response:

After the text file input, there is supposed to be just lowercase 'x' until the 512 characters limit is reached.

Read the block of up to 512 characters in 1 step.

#define N 512
char str[N];
size_t count = fread(str, 1, N, fp);

// Now copy in the x's
memset(str   count, N - count, 'x');

If you want to print the array, use a precision as str[] is not a string.

printf("<%.*s>\n", N, str);
  • Related