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
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.
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.