简体   繁体   English

为什么将字符串存储在字符中时只显示一个字符?

[英]Why do I only display one character when I store a string in a char?

[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'. [我正在制作一个随机单词生成器,所以我使用 time.h 库来使用 srand 并生成一个随机数...如果随机数 = 0,则 char (principal) = 'hola'。 But in CMD only shows the final character :( (Sorry for my bad english)但在 CMD 中只显示最后一个字符:((对不起,我的英语不好)

在此处输入图片说明

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;
}

In C and C++, a single quote (') means "character" (or one letter/number/symbol).在 C 和 C++ 中,单引号 (') 表示“字符”(或一个字母/数字/符号)。 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 ".双引号 (") 表示“字符串”。字符串文字(您在引号之间的代码中键入的字符串)将被视为字符数组,并在末尾添加一个空字符。这种类型的字符数组称为“c string”(不要与微软的“ 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.如果要处理字符串“hola”,则应使用std::string对象来存储它。 (You could use a char* , but I recommend using std::string until you understand the differences better.) (您可以使用char* ,但我建议您使用std::string直到您更好地理解差异。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM