打印出char数组,一个标签占用3个空格

时间:2017-09-25 02:59:23

标签: c file fopen fgets

我正在阅读以下data.txt文件:

b    1
b    2
b    3
b    4

这是中间的标签

我有以下代码,逐行打印,然后逐字符打印。

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

令我困惑的是它打印出来的东西:

b,  ,  ,  , 1, DONE PRINTING 

b,  ,  ,  , 2, DONE PRINTING 

b,  ,  ,  , 3, DONE PRINTING 

b,  ,  ,  , 4, DONE PRINTING 

我不明白字母和数字之间有3个空格。如果它们都是字符,那么该标签不应该只有一个空格,就是这样吗?

1 个答案:

答案 0 :(得分:1)

以下是对代码的最小化修改,并按照comment中的建议进行了更好的打印。

代码

#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");
}

以下是两个版本的数据文件的输出,一个带有声明的标签,另一个带有空格。

空间

请注意,数据是从问题中复制的。字母和数字之间有4个空格。代码还打印换行符;将它修改为在换行符或空字节上停止会很容易。

(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

标签

(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