sven tan
sven tan

Reputation: 149

'initializing' : truncation from 'int' to 'char'

#include "stdafx.h"
#include <iostream>
int main()
{
using namespace std;
char x = 'Game';
char y = x;
char z=y;
char z ='Play';
cout << z << endl;
cout << x << endl;
}

I am just a beginner of C++ and using Visual C++ 2012. When I compiled the above code, I get an error, "truncation from 'int' to 'char'". Can anyone tell me what I should do?

Upvotes: 0

Views: 5154

Answers (3)

Tio Pepe
Tio Pepe

Reputation: 3089

Without knowing what you really want to do ...

If you want to declare a string:

char * x = "Game";
string xs = "Game"; // C++

If you want to declare a char:

char y = 'G';
char z = y;
char z2 = x[0];  // remember: in C/C++, arrays begin in 0

You can't declare twice the same variable:

char z = y;
char z = 'Play';  // 'Play' is not a char and you can't redeclare z

So, final code seems like;

#include "stdafx.h"
#include <iostream>
int main()
{
    using namespace std;

    string x = "Game";
    char y = x[0];

    char z = y;
    string z2 = "Play";

    cout << z << endl;
    cout << x << endl;
}

Upvotes: 0

mathematician1975
mathematician1975

Reputation: 21351

You would be better off just using std::string

std::string x = "Game";
cout << x << endl;

You must use " instead of single quotes . Single quotes are used to represent a single char not an array

Upvotes: 2

user1508519
user1508519

Reputation:

§6.4.4.4.10

The value of an integer character constant containing more than one character (e.g., 'ab'), [...] is implementation-defined.

Chances are it's being treated as a long or similar type, which is "truncated" to fit into a char.

You need double quotes and to use std::string:

string x = "Game";

Upvotes: 1

Related Questions