C中的换行符从哪里来?

Where does the newline character come from in C?

我有以下程序,它将击球手的名字和他们的分数作为输入,并打印得分最高的击球手。我已经编写了以下算法并且它有效。但我面临的唯一问题是,在从用户那里获得输入后,换行符会显示在屏幕上。

#include<stdio.h>
#include<stdlib.h>
#include<limits.h>
#include<string.h>
int main()
{
    int n;
    char bat[100],maxs[100];
    int score,max=INT_MIN;
    scanf("%d",&n);
    while(n--)
    {
        scanf("%99[^,],%d",bat,&score);
        if(score>max)
        {
            max=score;
            strcpy(maxs, bat);
        }
    }
    printf("%s",maxs);
}

我不知道换行符是从哪里来的?请查看下面显示的输出。任何帮助表示赞赏。

你在那里换行,因为 scanf() 要求你按回车键继续。然后这个输入也被存储在字符串中。您可以删除末尾或开头的换行符(来源 here):

void remove_newline_ch(char *line)
{
    int new_line = strlen(line) -1;
    if (line[new_line] == '\n')
        line[new_line] = '[=10=]';
}

设想以下程序:

#include <stdio.h>
int main() { 
    int a;
    scanf("%d", &a);
    char string[100];
    scanf("%99[^,]", string);
    printf("-----\n");
    printf("%s", string);
}

现在执行看起来像:

10          # %d scans 10 and leaves the newline in input
string,     # then %99[^,] reads from the newline including it up until a ,
-----

string

How can I resolve this so that the newline is removed?

阅读换行符。 scanf 中的 space 字符忽略所有白色 space 字符。

scanf(" %99[^,]", string);

如果你想“准确”,你可以忽略一个换行符:

scanf("%*1[\n]%99[^,]", string);