大家好,我是编程新手。每当我尝试使用 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
请帮忙
最佳答案
#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;
}
关于c - 使用 printf 格式化列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26693223/