Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange characters appear when using strcat function in C++

Tags:

c++

strcat

I am a newbie to C++ and learning from the MSDN C++ Beginner's Guide.

While trying the strcat function it works but I get three strange characters at the beginning.

Here is my code

#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;

int main() {
    char first_name[40],last_name[40],full_name[80],space[1];
    space[0] = ' ';
    cout << "Enter your first name: ";
    gets(first_name);
    cout << "Enter your last name: ";
    gets(last_name);
    strcat(full_name,first_name);
    strcat(full_name,space);
    strcat(full_name,last_name);
    cout << "Your name is: " << full_name;
    return 0;
}

And here is the output

Enter your first name: Taher
Enter your last name: Abouzeid
Your name is: Y}@Taher Abouzeid

I wonder why Y}@ appear before my name ?

like image 575
taabouzeid Avatar asked May 21 '26 04:05

taabouzeid


2 Answers

You aren't initializing full_name by setting the first character to '\0' so there are garbage characters in it and when you strcat you are adding your new data after the garbage characters.

like image 164
John Avatar answered May 23 '26 18:05

John


The array that you are creating is full of random data. C++ will allocate the space for the data but does not initialize the array with known data. The strcat will attach the data to the end of the string (the first '\0') as the array of characters has not been initialized (and is full of random data) this will not be the first character.

This could be corrected by replacing

char first_name[40],last_name[40],full_name[80],space[1];

with

char first_name[40] = {0};
char last_name[40] = {0};
char full_name[80] = {0};
char space[2] = {0};

the = {0} will set the first element to '\0' which is the string terminator symbol, and c++ will automatically fill all non specified elements with '\0' (provided that at least one element is specified).

like image 30
Mekboy Avatar answered May 23 '26 18:05

Mekboy