Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to read abc.com like strings with scanf?

Im trying to read from stdin something like abc.com but a[0]=’\0′ after run scanf instead of ‘a’. Im using %[^.] to read all character until find a ‘.’.

#include <stdio.h>

int main() {

    char a[6];
    char b[4];

    int i = scanf("%[^.]%s", a, b);

    printf("%d\n", i);
    
    printf("a: %s\n", a);
    printf("b: %s\n", b);
    
    printf("%c\n", a[0]);
    printf("%c\n", a[1]);
    printf("%c\n", a[2]);
    
    if (a[3]=='\0') puts("why?");

    return 0;
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Trying char b[5]; will get you an output of

2
a: abc
b: .com
a
b
c

It indicates that you have read 5 characters into b, the fifth being the '\0' which overwrites a[0]. The first one being the '.', which intentionally is the NOT read by the format for a. You hence write beyond b (which is undefined behaviour and I should stop explaining right now….).
One of the possible behaviours of this UB is that the fifth read character for b is written beyond and into the first entry of a.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading