将2 Dimensional Char [] [] Array的特定范围复制到char *或std :: string

时间:2017-06-30 18:08:56

标签: c++ arrays char std

假设您阅读了标题,这里是伪代码中的一个小例子:

char inputChar[5][20];
{put data in array obviously}
char * outputChar;
copy(inputChar[2][7], inputChar[2][18], outputChar);
printf("%s", outputChar);

或可选(虽然我更喜欢上述版本):

char inputChar[5][20];
{put data in array obviously}
std::string outputString;
copy(inputChar[2][7], inputChar[2][18], outputString);
cout outputString; //I don't know how to use std::strings with printf

我已经尝试过std :: copy和memcpy,但我无法让它工作。结果要么给出了不属于字符串的随机字符,要么只是因为我不完全理解语法而导致编译器错误。

编辑: 这是我正在使用的实际代码: (假设这个例子中storeMenu已经分配了数据)

int line = 0
int frame5 = 11;
char storeMenu[9][13];
char * temp1 = new char[12];
char * temp2 = new char[12];
std::copy(&storeMenu[line+1][0], &storeMenu[line+1][frame5-10], temp1);
std::copy(&storeMenu[line][frame5-10], &storeMenu[line][12], temp2);

1 个答案:

答案 0 :(得分:2)

要使用outputChar,您需要一个指向角色位置的指针,您将在此处传递角色。您还需要初始化char inputChar[5][20] = {"abc","def","ghi01234567890","jkl"}; char * outputChar = new char[20]; auto last = copy(&inputChar[2][0], &inputChar[2][5], outputChar); *last = '\0'; printf("%s\n", outputChar);

std::string

或者使用char inputChar[5][20] = {"abc","def","ghi01234567890","jkl"}; string outputChar; copy(&inputChar[2][0], &inputChar[2][5], back_inserter(outputChar)); printf("%s\n", outputChar.c_str());

std::string

也将输入用作string inputChar[5] = {"abc","def","ghi01234567890","jkl"}; int fromChar = 2; // from (inclusive) ^ ^ int toChar = 5; // to (exclusive) ^ string outputChar; copy(inputChar[2].begin()+fromChar, inputChar[2].begin()+toChar, back_inserter(outputChar)); printf("%s\n", outputChar.c_str()); cout << outputChar << endl;

<div class="panel-heading clearfix">
      <h3 class="panel-title pull-left">Person Summary</h3>

  <div class="btns-container pull-right">
      <div style="display:inline-block">
        <button class="btn btn-default btn-margin">Save</button>
        <button class="btn btn-default btn-margin">Edit</button>
      </div>
    <div style="display:inline-block;vertical-align:middle;">
        <div class="onoffswitch">
          <input type="checkbox" name="onoffswitch" class="onoffswitch-checkbox" id="myonoffswitch" checked>
          <label class="onoffswitch-label" for="myonoffswitch">
            <span class="onoffswitch-inner"></span>
            <span class="onoffswitch-switch"></span>
          </label>
        </div>
      </div>
      </div>
  </div>