James Mitchell
James Mitchell

Reputation: 2467

Printing out char array, a tab takes up 3 spaces

I have the following data.txt file that I am reading:

b    1
b    2
b    3
b    4

It is a tab in-between

I have the following code to print it out, line by line, then character by character.

#include <stdio.h>
#include <stdlib.h>

int printCharArray(char *arr);

int main(int argc, char * argv[]){
    FILE * filePointer;
    filePointer = fopen("data.txt", "r");
    char singleLine[32]; 

    while(!feof(filePointer)){
        fgets(singleLine, 32, filePointer);
        printCharArray(singleLine);
    }

    fclose(filePointer);
    return 0;
}

int printCharArray(char *arr){
    int length = 5;
    printf("\n");

    int i = 0;
    for(i=0;i<length;++i){
        printf("%c, ", arr[i]);
    }
    printf("DONE PRINTING \n");

    return 0;
}

What confuses me is what it prints out:

b,  ,  ,  , 1, DONE PRINTING 

b,  ,  ,  , 2, DONE PRINTING 

b,  ,  ,  , 3, DONE PRINTING 

b,  ,  ,  , 4, DONE PRINTING 

I don't understand what there are 3 spaces between the letter and the number. If they're all chars, shouldn't there just be one space for the tab, and that's it?

Upvotes: 0

Views: 198

Answers (1)

Jonathan Leffler
Jonathan Leffler

Reputation: 753870

Here's a cleaned up minimal adaptation of your code, with better printing as suggested in my comment.

Code

#include <stdio.h>

void printCharArray(char *arr);

int main(void)
{
    char filename[] = "data.txt";
    FILE *filePointer = fopen(filename, "r");
    if (filePointer == NULL)
    {
        fprintf(stderr, "Failed to open file '%s' for reading\b", filename);
        return(1);
    }

    char singleLine[32];

    while (fgets(singleLine, sizeof(singleLine), filePointer) != 0)
        printCharArray(singleLine);

    fclose(filePointer);
    return 0;
}

void printCharArray(char *arr)
{
    printf("\n");
    for (int i = 0; arr[i] != '\0'; ++i)
        printf("(%d) %c, ", arr[i], arr[i]);
    printf("DONE PRINTING\n");
}

Here are the outputs from two versions of the data file, one with tabs as claimed and one with spaces.

Spaces

Note that the data was copied from the question. There are 4 spaces between the letter and the digit. The code also prints the newline; it would be easy to modify it to stop on newline or null byte.

(98) b, (32)  , (32)  , (32)  , (32)  , (49) 1, (10) 
, DONE PRINTING

(98) b, (32)  , (32)  , (32)  , (32)  , (50) 2, (10) 
, DONE PRINTING

(98) b, (32)  , (32)  , (32)  , (32)  , (51) 3, (10) 
, DONE PRINTING

(98) b, (32)  , (32)  , (32)  , (32)  , (52) 4, (10) 
, DONE PRINTING

Tabs

(98) b, (9)     , (49) 1, (10) 
, DONE PRINTING

(98) b, (9)     , (50) 2, (10) 
, DONE PRINTING

(98) b, (9)     , (51) 3, (10) 
, DONE PRINTING

(98) b, (9)     , (52) 4, (10) 
, DONE PRINTING

Upvotes: 1

Related Questions