1

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?

TemplateRex
  • 69,038
  • 19
  • 164
  • 304
Lake_Lagunita
  • 521
  • 1
  • 4
  • 20
  • 2
    This is an error on the Web site. It should be using `"` instead of `'`. In C++, `"` and `'` mean different things. – Raymond Chen Sep 15 '15 at 19:48
  • In c++, single quotes are used to denote a single char, while double quotes are used to denote a character string. So multiple characters require you use double quotes(`"`), while a single character uses a single quote (`'`). – StarPilot Sep 15 '15 at 20:09

1 Answers1

1

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.

Community
  • 1
  • 1
TemplateRex
  • 69,038
  • 19
  • 164
  • 304