大家好我是编程新手。每当我尝试使用printf格式化为列时,我会得到一些非常奇怪的行为。
for (int i = 0; i< count; i++) {
printf("%s %-20s %c\n",studentData[i].firstName, studentData[i].lastName, studentData[i].letterGrade);
}
我试图获得此输出
John Jones A
Bob Smith C
Sam Johnson B
etc... instead I get
John Jones A
Bob Smith C
Sam Johnson B
请帮助
答案 0 :(得分:0)
#include <stdio.h>
int main(void){
struct studendt {
char firstName[10];
char lastName[10];
char letterGrade;
} studentData[16] = {
{ "John", "Jones" , 'A'},
{ "Bob" , "Smith" , 'C'},
{ "Sam" , "Johnson", 'B'}
};
int count = 3;
for (int i = 0; i< count; i++) {
char name[20];//firstName_len(X-1) + lastName_len(X-1) + 1(' ') + 1(NUL) = 2X
snprintf(name, sizeof name, "%s %s",
studentData[i].firstName, studentData[i].lastName);
printf("%-20s %c\n", name, studentData[i].letterGrade);
}
return 0;
}