簡體   English   中英

'initializing':從'int'到'char'的截斷

[英]'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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM