-4

我在这个地方有错误:

strcpy_s(msgToGraphics, game.board_now());

错误是:

IntelliSense: no instance of overloaded function "strcpy_s" matches the argument list argument types are: (char [1024], std::string)    

这是 game.board_now 函数:

string Board::board_now()
{
return _board;
}

这是我尝试使用的其余代码strncpy_s()

#include "Pipe.h"
#include "Board.h"
#include <iostream>
#include <thread>

using namespace std;
void main()
{
    srand(time_t(NULL));

    Pipe p;
    bool isConnect = p.connect();

    string ans;
    while (!isConnect) {
        cout << "cant connect to graphics" << endl;
        cout << "Do you try to connect again or exit? (0-try again, 1-exit)" << endl;
        cin >> ans;

        if (ans == "0") {
            cout << "trying connect again.." << endl;
            Sleep(5000);
            isConnect = p.connect();
        }
        else {
            p.close();
            return;
        }
    }

    char msgToGraphics[1024];
    // msgToGraphics should contain the board string accord the protocol
    // YOUR CODE
    Board game;
    //strcpy_s(msgToGraphics, game.board_now()); // just example...

    p.sendMessageToGraphics("rnbkqbnrpppppppp################################PPPPPPPPRBNKQNBR0"); // send the board string

    // get message from graphics
    string msgFromGraphics = p.getMessageFromGraphics();

    while (msgFromGraphics != "quit") {
        game.change_board(msgFromGraphics);
        game.change_board_sq(msgFromGraphics);
        strcpy_s(msgToGraphics, game.board_now()); // msgToGraphics should contain the result of the operation

        // return result to graphics
        p.sendMessageToGraphics(msgToGraphics);

        // get message from graphics
        msgFromGraphics = p.getMessageFromGraphics();
    }

    p.close();
}

该代码基本上是用于国际象棋程序的,我在进行更改后尝试接收棋盘,但我不知道如何格式化他strcpy_s()以便将他放入数组并将其发送回给定的 exe。

4

2 回答 2

1

最简单的解决方案是制作msgToGraphicsa std::stringtoo,然后不使用 C 函数strcpy_s,而是分配给它来做同样的事情:

msgToGraphics = game.board_now();

如果您需要为char*底层数组获取非常量,您可以这样做(带有通常的警告):

p.sendMessageToGraphics(&msgToGraphics[0]);

但实际上您应该更改接口以不依赖传入的 char 数组。(提示:std::string改用。)

于 2017-01-02T17:42:02.850 回答
1

由于 C11 strcpy_s 是

1) `char *strcpy( char *dest, const char *src );`  
2) errno_t strcpy_s(char *restrict dest, rsize_t destsz, const char *restrict src);

strcpy_s与 (1) 相同,除了它可能会使用未指定的值破坏目标数组的其余部分,并且在运行时检测到以下错误并调用当前安装的约束处理函数:

  • src或 dest 是一个null指针
  • destsz为零或大于 RSIZE_MAX
  • destsz小于或等于strnlen_s(src, destsz);,换句话说,会发生截断
  • 源字符串和目标字符串之间会发生重叠

    1. 如果 dest <= 指向的字符数组的大小,则行为未定义,strnlen_s(src, destsz) < destsz;换句话说,destsz 的错误值不会暴露即将发生的缓冲区溢出。

    2. 作为所有边界检查函数,只有在 由实现定义并且用户在 include 之前定义 为整数常量 1strcpy_s时才保证可用。__STDC_LIB_EXT1____STDC_WANT_LIB_EXT1__string.h

有关更多信息,请参阅页面http://en.cppreference.com/w/c/string/byte/strcpy

于 2017-01-02T18:01:04.500 回答