-4

[Im making a random word generator, so i use time.h library to use srand and generate a random number... If random number = 0, then char (principal)= 'hola'. But in CMD only shows the final character :( (Sorry for my bad english)

enter image description here

The code is:

#include <iostream>
#include <stdlib.h>
#include <time.h>

using namespace std;

int main()
{
    int principal;
    char principal1;

    srand(time(NULL));

    principal = rand() % 2;

    if (principal == 0)
    {
        principal1 = 'hola';
        cout << principal1 << endl;
    }
    system("pause");
    return 0;
}
user4581301
  • 33,082
  • 7
  • 33
  • 54
Berszi
  • 13
  • 2
  • 10
    A char is a character. One character. Not a string. – Mat Feb 05 '18 at 18:58
  • 3
    `std::string principal1;` and `principal1="hola";` Don't forget to put `#include ` there. –  Feb 05 '18 at 19:03
  • 2
    You should have gotten compiler warnings about `'hola'`, if you didn't, crank up the compiler warning level. – Borgleader Feb 05 '18 at 19:14

1 Answers1

0

In C and C++, a single quote (') means "character" (or one letter/number/symbol). Only one character should be between two single quotes. Example:

'c'
'9'
'?'
'\n'  // Newline character
'\0'  // Null character

A double quote (") means "string". A string literal (a string you typed into the code between quotes) will be treated as an array of characters with a null character added on the end. This type of character array is called a "c string" (Not to be confused with Microsoft's "CString".

"Hi"  // Same as {'H', 'i', '\0'}
"Hello !\n"  // Same as {'H', 'e', 'l', 'l', 'o', ' ', '!', '\n', '\0'}

Trying to put a string inside single quotes is generally not good. It puts you into some weird territory of implemenation (ie compiler) specific behavior.

If you want to handle the string "hola", then you should use a std::string object to store it. (You could use a char*, but I recommend using std::string until you understand the differences better.)

Kyle A
  • 928
  • 7
  • 17