c - 使用 printf 格式化列

标签 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

请帮忙

最佳答案

#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/

相关文章:

c - 从大文件中读取数据到C中的结构中

c - 分割输入

c - 使用结构数组从文件读取时出现问题

c - 使用 GCC 的另一个目录中的静态库和 header

python - 在 Python 中编译 C DLL 并与之交互可以在 Unix 上运行,但不能在 Windows 上运行。这样做的正确方法是什么?

c++ - 实现任意精度的浮点库

c - 如何分离一个数组并将其存储到一个新数组中?

java - 如何制作Web App在线编译运行Java/C/PHP代码?

c - 在 Makefile 中,如何为每个 C 文件构建单独的可执行文件

c - 为什么字符上的 "~"运算符会产生更多字节?