代码之家  ›  专栏  ›  技术社区  ›  Aleph

如何使这篇文章连贯一致?[副本]

  •  0
  • Aleph  · 技术社区  · 6 月前

    我试图显示一行数据,我想整齐地显示数据。我使用了\t,但使用选项卡不一致:
    电流输出(大致):

    Location           City                     Price          Rooms   Bathrooms       Carpark         Type              Furnish
    Mont-Kiara       Kuala-Lumpur    1000000                   2            2        0         Built-up                  Partly
    Cheras   Kuala-Lumpur    310000                  3            2            0        Built-up         Partly
    

    我当前的代码:

    #include <stdio.h>
    #include <string.h>
    
    struct data_struct {
        char location[150];
        char city[150];
        long long int prices;
        int rooms;
        int bathroom;
        int carpark;
        char type[150];
        char furnish[150];
    } data[5000];
    
    void data_read(FILE *file) {
        char location[150];
        char city[150];
        long long int prices;
        int rooms;
        int bathroom;
        int carpark;
        char type[150];
        char furnish[150];
        
        char header[1000];
        fscanf(file, "%[^\n]\n", header);
        int i = 0;
        while(fscanf(file, "%[^,],%[^,],%lld,%d,%d,%d,%[^,],%[^\n]\n", location, city, &prices, &rooms, &bathroom, &carpark, type, furnish) == 8) {
            strcpy(data[i].location, location);
            strcpy(data[i].city, city);
            data[i].prices = prices;
            data[i].rooms = rooms;
            data[i].bathroom = bathroom;
            data[i].carpark = carpark;
            strcpy(data[i].type, type);
            strcpy(data[i].furnish, furnish);
            i = i + 1;
        }
    }
    
    void display_data(int row) {
        printf("Location \t City \t\t Price \t Rooms \t Bathrooms \t Carpark \t Type \t Furnish\n");
        for(int i = 0; i < row; i++) {
            printf("%s \t %s \t %lld \t %d \t %d \t %d \t %s \t %s\n", data[i].location, data[i].city, data[i].prices, data[i].rooms, data[i].bathroom, data[i].carpark, data[i].type, data[i].furnish);
        }
    }
    
    int main() {
        FILE *file = fopen("file(in).csv", "r");
        data_read(file);
            
        int t;
        scanf("%d", &t);
    
        display_data(t);
            
        return 0;
    }    
    

    我试着在网上寻找解决方案,但没有找到任何有用的东西。有没有办法让它在C中看起来像这样?

    预期输出看起来像这样(没有边框):

    地点 城市 价格 房间 浴室 停车场 类型 家具
    基亚拉山 吉隆坡 1000000 2. 2. 0 建成 部分
    Cheras 吉隆坡 310000 3. 2. 0 建成 部分
    1 回复  |  直到 6 月前
        1
  •  1
  •   Chris    6 月前

    尽管没有您要打印的文件的内容,但很明显,这里的答案是使用宽度字段 %s format specifier 以确保对齐。

    例如。

    printf("%-8s %-8s %-8s\n", "A", "B", "C");
    printf("%-8d %-8d %-8d\n", 42, 56, 896);
    

    打印:

    A        B        C
    42       56       896
    

    或者也许:

    printf("%-8s %-8s %-8s\n", "A", "B", "C");
    printf("%8d %8d %8d\n", 42, 56, 896);
    printf("%8.2f %8.2f %8d\n", 3.14, 9.23454, 7);
    
    A        B        C
          42       56      896
        3.14     9.23        7