[英]'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;
}
我只是C ++的初学者,并且使用Visual C ++2012。编译以上代码时,出现错误, "truncation from 'int' to 'char'
”。 谁能告诉我该怎么办?
您最好只使用std::string
std::string x = "Game";
cout << x << endl;
您必须使用"
而不是单引号。单引号用于表示单个char
而不是数组。
§6.4.4.4.10
包含多个字符(例如,“ ab”)的整数字符常量的值由实现定义。
可能会将其视为long
或类似类型,被“截断”以适合char
。
您需要双引号并使用std::string
:
string x = "Game";
不知道你到底想干什么...
如果要声明一个字符串:
char * x = "Game";
string xs = "Game"; // C++
如果要声明一个字符:
char y = 'G';
char z = y;
char z2 = x[0]; // remember: in C/C++, arrays begin in 0
您不能两次声明相同的变量:
char z = y;
char z = 'Play'; // 'Play' is not a char and you can't redeclare z
因此,最终代码看起来像;
#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.