C++文本动画错误 C2397

C++ text animation Error C2397

本文关键字:C2397 错误 动画 文本 C++      更新时间:2023-10-16

我从YouTube视频中写下了这段代码(来自Husam Haj(:https://www.youtube.com/watch?v=C2k-xiLmNSQ

这段代码应该使用C++对文本进行动画处理(请参阅视频(,但问题是这段代码不起作用,因为我从Visual Studio 2017收到以下消息:

"错误 C2397:从'int'到'SHORT'的转换需要缩小转换范围">

正在互联网上研究,我发现有人已经要求帮助使用相同的代码,但不是解决方案:http://www.dreamincode.net/forums/topic/358635-i-need-some-help/

我将不胜感激任何帮助

下面是代码:

#include "stdafx.h"
#include <string>
#include <string.h>
#include <windows.h>
#include <iostream>
using namespace std;
void Display(string[], const int);
int main()
{
const int arr_size = 12;
string myInfo[arr_size] = { " Animated text example",
  "     Brooklyn College",
  "  Pre-Engineering Program",
 };
 Display(myInfo, arr_size);
 return 0;
}
void Display(string arr_string[], int arr_size)
{
 HANDLE screen = GetStdHandle(STD_OUTPUT_HANDLE);
COORD pos[18] = { { 0,6 },{ 0,7 },{ 0,9 },{ 0,11 },{ 0,13 },{ 0,15 },
 { 0,17 },{ 0,19 },{ 0,21 },{ 0,23 },{ 0,25 },{ 0,27 },
 { 0,29 },{ 0,31 },{ 0,33 },{ 0,35 },{ 0,37 },{ 0,39 } };
 for (int k = 0; k<arr_size; k++)
{
  for (int j = arr_string[k].size(); j >= 0; j--)
{
   for (int i = 0; i <= j; i = i++)
{
    SetConsoleCursorPosition(screen, pos[k]);
    cout << " " << endl;
    pos[k].X++;
    SetConsoleCursorPosition(screen, pos[k]);
    cout << arr_string[k][j] << endl;
    Sleep(1);
}
pos[k] = {0,k+1}; //HERE THE MISTAKE!
}
}
}

抱怨的是您将一个 32 位数字塞入 16 位空间,可能会丢失数据。本来以为这是一个警告,而不是编译器错误。

我不知道将整数文字强制为 16 位整数的后缀,所以一个快速而俗气的解决方案是投射

pos[k] = {(SHORT)0,(SHORT)(k+1)}; 

你会有一个类似的问题

for (int j = arr_string[k].size(); j >= 0; j--)

因为您要将无符号整数从 size() 分配给有符号整数。

for (size_t j = arr_string[k].size(); j >= 0; j--)

应该解决这个问题。 当我们在这里时,当心

for (int i = 0; i <= j; i = i++)

因为你不知道你先得到增量(i++(还是分配(i=(。

pos是一个COORD数组。当我按 F12(转到定义(时,它会显示:

typedef struct _COORD {
    SHORT X;
    SHORT Y;
} COORD, *PCOORD;

SHORT只是short的typedef

。将类型为

intk + 1分配给类型为 short COORD::y 的 。类型 short 的变量比 int (可能值范围较小(,因此编译器理所当然地抱怨。

要修复错误,请声明short k或使用编译器喜欢的"缩小转换"的static_cast

pos[k] = {0, static_cast<SHORT>(k+1)}; 

这只能正常工作,因为控制台屏幕坐标在足够小的范围内以适应short