The following code
#include <iostream>
#include <string>
int main()
{
std::string s = "abc";
for (char c : s)
std::cout << (int) c << " ";
}
prints "97 98 99 ".
The following code
#include <iostream>
int main()
{
for (char c : "abc")
std::cout << (int) c << " ";
}
prints "97 98 99 0 ".
Where is the extra 0 coming from in the second code?
Strings are actually one-dimensional array of characters terminated by a null character '\0'. Thus a null-terminated string contains the characters that comprise the string followed by a null.
'\0' is referred to as NULL character or NULL terminator It is the character equivalent of integer 0(zero) as it refers to nothing. In C language it is generally used to mark an end of a string.
The \0 is treated as NULL Character. It is used to mark the end of the string in C. In C, string is a pointer pointing to array of characters with \0 at the end. So following will be valid representation of strings in C.
string at() in C++std::string::at can be used to extract characters by characters from a given string. Syntax 2: const char& string::at (size_type idx) const idx : index number Both forms return the character that has the index idx (the first character has index 0).
The literal "abc"
is a const char[4]
type: the final element is the NUL terminator (with value 0).
In the second snippet, the value of the NUL terminator is printed as the code is describing an iteration over that entire const char[4]
array.
In the first snippet, the underlying iterator technology of the std::string
class sets the end iterator (which is not reached in the short form for
loop) to the NUL terminator. This behaviour is consistent with s.size()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With