使用printf格式化列

时间:2014-11-01 21:02:42

标签: c

大家好我是编程新手。每当我尝试使用printf格式化为列时,我会得到一些非常奇怪的行为。

for (int i = 0; i< count; i++) {
       printf("%s %-20s %c\n",studentData[i].firstName, studentData[i].lastName,       studentData[i].letterGrade);
    }

我试图获得此输出

John Jones &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; A

Bob Smith &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;C 

Sam Johnson &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;B

etc... instead I get

John Jones&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;A

Bob Smith&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;C

Sam Johnson &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;B

请帮助

1 个答案:

答案 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;
}