” “在行之间打印额外的空格?

问题描述 投票:0回答:1

我遇到了一个问题“ ”似乎在“Credits?”和 printf(“您想打印以下四组中的哪一组?”)之间打印一个额外的空行;。问题出现在我的代码的这一部分中:

// collect student info
    for (int i = 0; i < numStudents; i++) {
        printf("Please input information for student %d:\n", i + 1);
        printf("Name? ");
        scanf("%s", students[i].name);

        printf("Sex('M' or 'F')? ");
        scanf(" %c", &students[i].sex);

        printf("Credits?\n");
        scanf("%d", &students[i].credits);
    }

    // create options 1-4
    printf("Which of the following four groups do you want to print? ");
    printf("(1) male students (2) female students (3) odd credits (4) even credits\n");
    int option;
    scanf("%d", &option);

仅供参考,正确的输出应该是:

Name? Sex('M' or 'F')? Credits? 
Which of the following four groups do you want to print?

但是,我得到的是:

Name? Sex('M' or 'F')? Credits? 

Which of the following four groups do you want to print?

我尝试删除“ " 在

"Credits?"
之后,以及插入一个 " " 在
"Which of the following four groups do you want to print?"
前面,但这似乎删除了两个换行符,将两行输出打印在一行上,如下所示:

Name? Sex('M' or 'F')? Credits? Which of the following four groups do you want to print?
由于这个空间,我们在这堂课中使用的评分软件给了我 0%,我不知道还能尝试什么。

c whitespace
1个回答
0
投票

解决此问题的一种方法是在读取整数后清除输入缓冲区。

// collect student info
for (int i = 0; i < numStudents; i++) {
    printf("Please input information for student %d:\n", i + 1);
    printf("Name? ");
    scanf("%s", students[i].name);

    printf("Sex('M' or 'F')? ");
    scanf(" %c", &students[i].sex);

    printf("Credits?\n");
    scanf("%d", &students[i].credits);

    // Clear input buffer
    while (getchar() != '\n'); // Read and discard characters until newline is found
}

// create options 1-4
printf("Which of the following four groups do you want to print? ");
printf("(1) male students (2) female students (3) odd credits (4) even credits\n");
int option;
scanf("%d", &option);

// Clear input buffer
while (getchar() != '\n'); // Read and discard characters until newline is found
© www.soinside.com 2019 - 2024. All rights reserved.