1

In chapter 3.9.1 "Safe conversions," from Stroustrup's Programming, he has code to illustrate a safe conversion from int to char and back.

#include<iostream> #include<string> #include<vector> #include<algorithm> #include<cmath> using namespace std; int main() { char c='x'; int i1=c; int i2='x'; char c2 = i1; cout << c <<'<< i1 << ' << c2 << '\n'; return 0; } 

It's supposed to print x 120 xto the screen.

However, I can't get it to work and I'm not sure why. The result I get is x1764834364x.

I also get a 3 warnings (in Xcode 6.3.1).

  • Multi-character character constant.
  • Character constant too long for its type.
  • Unused variable i2.

What causes this?

3
  • 7
    Are you sure you've copied the code correctly? Using single quotes around '<< i1 << ' is, as the message says, a multi-character character constant which is almost never what you want. Perhaps you want cout << c << ' ' << i1 << ' ' << c2 << '\n'; to add spaces between the things you're printing. Commented Apr 28, 2015 at 22:47
  • I copied it exactly as it is in the book, but you're right Greg. If I do as you suggest, I get the desired answer. I'm disappointed the samples in the book aren't more precise, but I appreciate your help. Commented Apr 28, 2015 at 22:51
  • 2
    Well, you're quite right. I looked on page 79 in Google Books and sure enough, the code in the book is definitely incorrect. Commented Apr 28, 2015 at 23:01

2 Answers 2

3

The problem is here:

'<< i1 << ' 

The compiler gives you a warning (gcc at least):

warning: character constant too long for its type

It believes that you are trying to display a single char (the content between the apostrophes), but you are in fact passing multiple chars. You probably just want to add spaces, like

' ' << i1 << ' ' 
Sign up to request clarification or add additional context in comments.

Comments

3

I would like to add some related information that might be useful for people with similar situation:

When you use single quotes to print something longer than a character you would get such weird output. For example:

cout << 'a'<<' '<<'a'; // output will be something like: a538946288a 

on the other hand single quotes with single character:

cout << 'a'<<' '<<'a'; // output will be: a a 

if you want to give more than one space character you may use double quotes.

In your code:

int main() { char c='x'; // c is character 'x' int i1=c; // i1 is its integer value int i2='x'; // i2 has the integer value but it`s never used char c2 = i1; // c2 is the character 'x' cout << c <<" "<< i1 <<" "<<c2 << '\n'; // should print: x 120 x // By using double quotes you may enter longer spaces between them // vs. single quotes puts only a single space. return 0; } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.