Here is a loop that goes through each character in "(Level:"
. It adds something to the end which is messing up the rest of my code.
#include <iostream>
int main() {
std::cout << "Output:" << std::endl;
for (char letter : "(Level:") {
std::cout << "'" << letter << "'" << std::endl;
}
return 0;
}
Output:
'('
'L'
'e'
'v'
'e'
'l'
':'
''
I'm new to C and I don't understand what's happening.
CodePudding user response:
"(Level:"
has type const char[8]
, and is equivalent to { '(', 'L', 'e', 'v', 'e', 'l', ':', '\0' }
.
You can easily see this is the case by casting the letter to int
before printing. Demo
This happens, because string literals (anything "..."
) are C-strings, which are zero terminated. If you want strings to have a size instead of a zero terminator, you can use a string_view
literal:
#include <iostream>
#include <string_view>
using namespace std::literals::string_view_literals;
int main() {
std::cout << "Output:" << std::endl;
for (char letter : "(Level:"sv) {
std::cout << "'" << letter << "' (" << static_cast<int>(letter) << ")\n";
}
return 0;
}
CodePudding user response:
Cause the strings in C are all ended with '\0', we can't see it but it really exists. This hidden '\0' can marks the end of a string and can be read by your 'for' statement. You can add an 'if' statement in your 'for' statement to deal with '\0'.
#include <iostream>
int main() {
std::cout << "Output:" << std::endl;
for (char letter : "(Level:") {
if (letter != '\0')
std::cout << "'" << letter << "'" << std::endl;
}
return 0;
}