Tim Elhajj
Tim Elhajj

Reputation: 895

Char-to-int conversion in C++

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).

What causes this?

Upvotes: 1

Views: 150

Answers (2)

erol yeniaras
erol yeniaras

Reputation: 3797

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

Upvotes: 3

vsoftco
vsoftco

Reputation: 56547

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 << ' '

Upvotes: 3

Related Questions