2017-01-02 82 views
-3

嗨,大家好我在這個地方有錯誤:C++ strcpy_s智能感知錯誤

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 FUNC:

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。 感謝所有嘗試幫助的人!

+3

爲什麼不'msgToGraphics'一個'的std :: string'呢?你可以避免很多麻煩,避免使用簡單的'char'數組,在這種情況下,你可以通過operator =賦值給另一個字符串,如'msgToGraphics = game.board_now();'。 –

+0

,因爲它必須是數組,因爲這是接口接收的信息 – SimpleNigal

+1

這不是一個好的理由。您可以使用string :: c_str()將字符指針傳遞給您的API。 –

回答

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. 如果字符ar的大小未定義ray指向dest < = strnlen_s(src, destsz) < destsz;換句話說,destsz的錯誤值不會暴露即將發生的緩衝區溢出。

    2. 由於所有邊界檢查功能,strcpy_s僅保證可供如果__STDC_LIB_EXT1__由實現所定義,並且如果用戶包括string.h之前定義__STDC_WANT_LIB_EXT1__爲整數常數1。

請參閱該頁面瞭解更多信息http://en.cppreference.com/w/c/string/byte/strcpy

1

最簡單的解決辦法是讓msgToGraphics一個std::string過,然後而是採用了C函數strcpy_s的,只是分配給它做同樣的事情:

msgToGraphics = game.board_now(); 

如果你需要得到一個非-const char*爲基礎數組,你可以做這樣的(與通常的警告):

p.sendMessageToGraphics(&msgToGraphics[0]); 

不過說真的,你應該更改爲不依賴於字符數組的接口在傳遞(提示:使用std::string代替。)