Is there some problem with the following c code

When i compile and run this program my input string is not same as output.

#include<stdio.h>
int main()
{
    int n; char ch[100];
    scanf("%d : %5s", &n, ch);
    printf("%d : %s", n, ch); // there is some problem with output of the string
    return 0;
}

input:

45
asdf

output:

45 : ∟sëuⁿ■a

>Solution :

The scanf part will read until it hits the colon, but it will not read the colon itself, which means the following integer will not be read correctly and the rest of the string will be parsed incorrectly (if at all).

Try removing the colon (:) from the scanf

#include <stdio.h>
int main()
{
    int n; char ch[100];
    scanf("%d %5s", &n, ch);
    printf("%d : %s", n, ch);
    return 0;
}

Leave a Reply