I do not understand why by entering abcd efgh, in string1 [0] and string1 [1], you are not showing me a, b
In C ++ the character strings end with the character '"abc"
'
, that is, the string "abcefgh
"
will be stored as cadena1
. Put another way, if your idea is to store a string of 3 characters you need an array with capacity for at least 4 elements ... if you do not do that you will overflow the array and tread memory of other processes.
In your case it's easy to see:
0h
1(signo raro)
What has happened is that cadena1
has stepped on the memory of cadena2
:
0x01 0x02 0x03 0x04 0x05 0x06 0x07 0x08
| cadena2 | cadena1 | otra memoria
abcd -> | | a b c | d std::cout << "cadena1: " << cadena1 << '\n'
<< "cadena2: " << cadena2 << '\n';
efgh -> | e f g | h cadena1: h
cadena2: efgh
c | d cadena[1] = '#';
You can check that this is the case by displaying cadena1
and std::string
:
cadena1: h#cd
cadena2: efgh#cd
The following will be printed:
// Podran almacenar hasta 4 caracteres
char cadena1[5];
char cadena2[5];
And we can even go further if we modify the second character of cadena1
:
std::string cadena1, cadena2;
Then the output will change to:
std::cin >> cadena1;
To avoid this problem you have to ensure that the arrangements are large enough to cover your needs:
0h
1(signo raro)
Or ... you can choose to use char*
, which programming in C ++ makes all the sense of the world and you will not have to worry about the length of the strings entered by the user
0x01 0x02 0x03 0x04 0x05 0x06 0x07 0x08
| cadena2 | cadena1 | otra memoria
abcd -> | | a b c | d std::cout << "cadena1: " << cadena1 << '\n'
<< "cadena2: " << cadena2 << '\n';
efgh -> | e f g | h cadena1: h
cadena2: efgh
c | d cadena[1] = '#';
Why do not you put me directly abc in the first array and def in the second?
Because the program does not know what your intentions are and it just does what you ask ... when you do:
cadena1: h#cd
cadena2: efgh#cd
The compiler sees that char[]
is of type std::string
(a pointer to char) and is limited to storing characters in that array until it encounters a space, a line break or the buffer is emptied, happen before.
Since you are using low level programming ( %code% instead of %code% ) it is your responsibility to ensure that you do not overflow the buffer.