3

C++ を使用せずに入力から文字列 (任意のサイズ) を取得するように求められましたstring。char 配列に動的にスペースを割り当てることを考え、SO 自体から次の実装を取得しました。しかし、それが適切な実装であるかどうかはわかりません。名前に要素の数を入力する必要のない、これに対するより良い実装はありますか?

#include<iostream>
int main()
{
    int size = 0;
    std::cout << "Enter the size of the dynamic array in bytes : ";
    std::cin >> size;
    char *ptr = new char[size];

    for(int i = 0; i < size;i++)
        std::cin >> *(ptr+i);
}
4

2 に答える 2

-1

これを行う方法は次のとおりです。

#include <iostream>
#include <cstring>

using namespace std;

char *s;
int buflen = 10;
int len = 0;

int main() {
  s = new char[buflen];
  char c;
  while (cin >> c) {
    s[len++] = c;
    if (len >= buflen) {
      // need to allocate more space
      char *temp = new char[buflen * 2];
      memcpy(temp, s, buflen);
      delete s;
      s = temp;
      buflen *= 2;
    }
  }
  s[len++] = '\0';

  cout << "Your string is: " << s << endl;
}
于 2013-08-17T08:57:37.760 に答える