[英]'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'
". 我只是C ++的初学者,并且使用Visual C ++2012。编译以上代码时,出现错误,
"truncation from 'int' to 'char'
”。 Can anyone tell me what I should do? 谁能告诉我该怎么办?
You would be better off just using std::string
您最好只使用
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 您必须使用
"
而不是单引号。单引号用于表示单个char
而不是数组。
§6.4.4.4.10 §6.4.4.4.10
The value of an integer character constant containing more than one character (eg, 'ab'), [...] is implementation-defined.
包含多个字符(例如,“ ab”)的整数字符常量的值由实现定义。
Chances are it's being treated as a long
or similar type, which is "truncated" to fit into a char
. 可能会将其视为
long
或类似类型,被“截断”以适合char
。
You need double quotes and to use std::string
: 您需要双引号并使用
std::string
:
string x = "Game";
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.