-1

I have the following program that takes as input the batsman names and their scores and prints the batsman with the highest score. I have written the following algorithm and it works. But the only problem I am facing is that, the newline character is getting displayed on the screen after the input has been gotten from the user.

#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);
}

I have no clue of where the newline is coming from? Please see the output shown below. Any help is appreciated. enter image description here

S M Vaidhyanathan
  • 320
  • 1
  • 4
  • 13

2 Answers2

3

Imagine the following program:

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

Now execution could look like:

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?

Read the newline. A space character in scanf ignores all whitespace charactesrs.

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

You could ignore a single newline character, if you want to be "exact":

scanf("%*1[\n]%99[^,]", string);
KamilCuk
  • 120,984
  • 8
  • 59
  • 111
0

You're getting a newline there because scanf() requires you to hit enter to proceed. This enter then gets stored in the string as well. You could remove newlines at the end or beginning with something like this (source here):

void remove_newline_ch(char *line)
{
    int new_line = strlen(line) -1;
    if (line[new_line] == '\n')
        line[new_line] = '\0';
}
  • 3
    `scanf` does not require any newline. If you're running the program in line mode (cooked mode), it won't see input from stdin until a line is available. – Paul Hankin Jul 26 '20 at 08:09
  • 1
    This is an overkill for this question. Prepending a space to `%99[^,]` is the simplest solution. And the code above will result in undefined behaviour if the string pointed to by `line` is empty, that is `""`. – M. Nejat Aydin Jul 26 '20 at 08:58