如何垂直打印数据



在这段代码中,我使用了char指针变量并打印它们,因为我想使用指针保存数据,但打印应该是垂直的o变量,而不是水平打印。我不知道怎么做?

给定输出

Name: FirstSecondThirdFour
DOB: FirstSecondThirdFour
ID: FirstSecondThirdFour
Phone: FirstSecondThirdFour

预期输出

Name: First
DOB: Second
ID: Third
Phone: Four

代码

#include <stdio.h>  
#include <string.h>
#include <stdlib.h>
#define STRING_LEN 200
int main(){
int i;
char *one = "First", *two = "Second", *three = "Third", *four = "Four";
char *listing[] = {"Name", "DOB", "ID", "Phone"};
for(i=0; i<4; i++){
printf("%s: %s%s%s%sn", listing[i], one, two, three, four);
}   
return 0;
}

如果您想将字符串变量保留为它们的名称(例如char *onechar *two(,您可以将它们推送到列表中,那么您的代码将如下所示:

#include <stdio.h>  
#include <string.h>
#include <stdlib.h>
#define STRING_LEN 200
int main(){
int i;
char *one = "First", *two = "Second", *three = "Third", *four = "Four";
char *listing[] = {"Name", "DOB", "ID", "Phone"};
char *strs[] = {one, two, three, four};
for(i=0; i<4; i++){
printf("%s: %sn", listing[i], strs[i]);
}   
return 0;
}

您可以使用switch

int main(){
int i;
char *listing[] = {"Name", "DOB", "ID", "Phone"};
for(i=0; i<4; i++){
char *data = "";
switch(i) {
case 0: data = "first";
case 1: data = "second";
case 2 data = "third";
case 3: data = "fourth";
}
printf("%s: %s%sn", listing[i], data);
}   
return 0;
}

或者您可以将索引映射到字符串,如下所示

#include <stdio.h>  
#include <string.h>
#include <stdlib.h>
#define STRING_LEN 200
int main(){
int i;
char *mapper[] = {"First", "Second", "Third", "Four"};
char *listing[] = {"Name", "DOB", "ID", "Phone"};
for(i=0; i<4; i++){
printf("%s: %s%sn", listing[i], mapper[i]);
}   
return 0;
}

或者使用如下结构来维护记录。

#include <stdio.h>  
#include <string.h>
#include <stdlib.h>
#define STRING_LEN 200
typdef struct {
char *data;
char *pos;
} List;
int main(){
int i;
List listing[] = {{"Name", "First"}, {"DOB, "Second"}, {"ID", "Third"}, {"phone", "Four"};

for(i=0; i<4; i++){
printf("%s: %s%sn", listing[i].data, listing[i].pos);
}   
return 0;
}

根据您在注释中所写的内容(真正应该在问题本身中的信息!(,您需要使用结构的数组

也许类似于:

struct person
{
char name[100];
char dob[20];
char id[10];
char phone[20];
};

然后只是为了测试:

struct person persons[] = {
{ "Jake"  , "2013-06-07", "id-01", "123-456-789" },
{ "Jarren", "2019-10-03", "id-02", "456-789-012" }
};
size_t num_persons = 2;  // Number of persons in the array
for (size_t i = 0; i < num_persons; ++i)
{
printf("Name   : %sn", persons[i].name);
printf("DOB    : %sn", persons[i].dob);
printf("ID     : %sn", persons[i].id);
printf("Phone  : %sn", persons[i].phone);
}

最新更新