Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

C++ weird output with strings

+5 votes
asked Feb 18 by gta6isnotfree (430 points)
I tried this in C++ but it prints some garbage: #include using namespace std; int main() { char str[5] = "Hello"; cout << str << endl; return 0; } Why is it not printing “Hello” correctly? How do I fix it?

3 Answers

0 votes
answered Feb 18 by Filip Necula (280 points)
If you want to work with strings I recomend using the <string> library to avoid such problems
0 votes
answered Feb 18 by Peter Minarik (101,340 points)
edited Feb 18 by Peter Minarik

Your code doesn't even compile.

C strings are zero-terminated strings. That is, a zero character ('\0') indicates the end of the string. For this, "Hello" is not 5 characters long, but 6: "Hello\0". Note: '\0' is a single character; the backslash before the 0 is the escape sequence.

char str[6] = "Hello";

would solve your problem.

Or you just do not specify the size, and the compiler will figure it out for you:

char str[] = "Hello";

Or you do not copy the string literal into an array (if you do not have to), but just reference it via its memory address:

const char * str = "Hello";

In the latter case, remember, you do not have a copy of the string literal "Hello". You are pointing to the string literal, and as such, it must not be modified (e.g., by saying str[0] = 'h'; hence the type is const char *). You can still point somewhere else by str though, e.g.: str = "This works too".

0 votes
answered Feb 20 by aylin (140 points)
#include <iostream>

using namespace std;
int main() {
    char str[6] = "Hello";
    cout << str << endl;
    return 0;
    
}

thats the correct code , Hello has 6 characters including null
Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and receive answers from other members of the community.
...