Lake_Lagunita
Lake_Lagunita

Reputation: 553

c-style string using single quote or double quote?

I was studying the c-style string tutorial on this website: http://www.learncpp.com/cpp-tutorial/66-c-style-strings/ and there's a code snippet:

#include <iostream>

int main()
{
    char mystring[] = "string";
    std::cout << mystring << " has " << sizeof(mystring) << 'characters.\n';
    for (int index = 0; index < sizeof(mystring); ++index)
        std::cout << static_cast<int>(mystring[index]) << " ";

    return 0;
}

the result should be : string has 7 characters. 115 116 114 105 110 103 0

however, when I use Xcode to run it, it shows that : *string has 71920151050115 116 114 105 110 103 0 *

and also got a warning for 'characters.\n'. the warning said that "character too long for its type, multi-character character constant".

thus I changed this to "characters.\n" (replace ' with ") and the the result is as expected.

My question is whether this problem is due to the code itself or due to my compiler? is it the book's fault or my fault?

Upvotes: 1

Views: 927

Answers (1)

TemplateRex
TemplateRex

Reputation: 70526

There is a typo in your code: use double quotes around "characters.\n":

std::cout << mystring << " has " << sizeof(mystring) << "characters.\n";

Live Example.

The output you saw with the sinqle quotes was a multi-character literal that has type int and an implementation defined value. See this Q&A.

Upvotes: 1

Related Questions