I'm trying to display a row of data, I want to display the data neatly. I used \t, but using tab is inconsistent:
Current output (roughly):
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
My current code:
#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;
}
I tried looking for a solution for this online, but haven't found anything useful. Is there a way to make it look like this in C?
Expected output would look something like this (without the border):
Location | City | Prices | 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 |
Despite not having the contents of the file you're printing, it's clear that the answer here is to use the width field with the %s
format specifier to ensure alignment.
E.g.
printf("%-8s %-8s %-8s\n", "A", "B", "C");
printf("%-8d %-8d %-8d\n", 42, 56, 896);
Prints:
A B C
42 56 896
Or perhaps:
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