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

scanf skipping string with a defined size with a proceeding space

I’m trying to read 3 different strings of max 15 characters each. When I try to read them with scanf("%s %s %s", a, b, c), only the last one is picked up (I’m asuming the spaces between every string has something to do with this).

#include <iostream>
#include <string.h>

using namespace std;

#define DIM 15

int main()
{
    char a[DIM], b[DIM], c[DIM];

    scanf("%s %s %s", a,b,c);
    cout << a << endl;
    cout << b << endl;
    cout << c << endl;
    cout << "Cadenes introduides: " << a << " " << b << " " << c << endl;
}

the input is CadenaDe15chars CadenaDe15chars CadenaDe15chars

And I’m only seeing

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



CadenaDe15chars
Cadenes introduides:   CadenaDe15chars

when the actual output should be

CadenaDe15chars
CadenaDe15chars
CadenaDe15chars
Cadenes introduides: CadenaDe15chars CadenaDe15chars CadenaDe15chars

I’m kinda new to c++ so I don’t really know how to make scanf ignore the whitespace, I’ve found examples with strings delimited by a new line \n, but not with a space.

>Solution :

This call

scanf("%s %s %s", a,b,c);

invokes undefined behavior because at least this input "CadenaDe15chars" contains 15 characters. So the appended terminating zero character ‘\0’ will be written by the function outside the corresponding array used as an argument.

You should at least declare the macro constant like

#define DIM 16

to reserve space in the arrays for potentially appended zero character.

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