Ad

Where Does The Newline Character Come From In C?

- 1 answer

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

Ad

Answer

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);
Ad
source: stackoverflow.com
Ad