2017-11-30 22 views
-1

C++で動的配列を作成し、ユーザがexitと入力するまで名前を入力する必要があります。連続した文字列入力用のC++動的配列

さらに多くの名前を尋ねて、動的文字列配列に記録してから、ユーザーが望むだけ多くの名前をランダムに選択する必要があります。

私は乱数部分を理解することができるはずですが、連続入力は私に問題を与えています。長さ変数の値の変更を継続する方法がわかりません。

#include <iostream> 
#include <string> 

using namespace std; 

int main() 
{ 
    int length; 

    string* x; 
    x = new string[length]; 
    string newName; 

    for (int i = 0; i < length; i++) 
    { 
     cout << "Enter name: (or type exit to continue) " << flush; 
     cin >> newName; 
     while (newName != "exit") 
     { 
      newName = x[i]; 
     } 
    } 
    cout << x[1] << x[2]; 

    int qq; 
    cin >> qq; 
    return 0; 
} 

ご協力いただければ幸いです。

+2

'length'には値がありませんが、あなたは"未定義の長さ "の配列を作ることができると思います - 配列のサイズを動的に変更しようとしていません。 forループ内のwhileループはナンセンスです。 – John3136

+0

'std :: vector'を考えてみましょう。 –

+0

ちょっと磨いてみると、 'const int length = 3;'と 'x [i] = newname'と' cout << x [0] .... ' – macroland

答えて

-1

いくつかのエラー:

  1. lengthはあなたがnewName = x[i];
  2. xに配列の割り当てられていない値x[i]newNameを上書きしている
  3. が動的に新しい配列に再割り当てされることはありません値を割り当てられることはありません異なるlength

'動的に新しいが割り当てられているx[i] = newName;

  • xを取得する方向を逆に

    1. lengthが開始
    2. でデフォルト値が割り当てられます言及したエラーへの対処

      #include <iostream> 
      #include <string> 
      
      using namespace std; 
      
      int main() 
      { 
          int length = 2; // Assign a default value 
          int i = 0;  // Our insertion point in the array 
      
          string* x; 
          x = new string[length]; 
          string newName; 
      
          cout << "Enter name: (or type exit to continue) " << flush; 
          cin >> newName; // Dear diary, this is my first input 
      
          while (newName != "exit") 
          { 
           if (i >= length) // If the array is bursting at the seams 
           { 
            string* xx = new string[length * 2]; // Twice the size, twice the fun 
      
            for (int ii = 0; ii < length; ii++) 
            { 
             xx[ii] = x[ii]; // Copy the names from the old array 
            } 
      
            delete [] x; // Delete the old array assigned with `new` 
            x = xx;  // Point `x` to the new array 
            length *= 2; // Update the array length 
           } 
      
           x[i] = newName; // Phew, finally we can insert 
           i++;   // Increment insertion point 
      
           cout << "Enter name: (or type exit to continue) " << flush; 
           cin >> newName; // Ask for new input at the end so it's always checked 
          } 
      
          cout << x[1] << x[2]; // Print second and third names since array is 0-indexed 
      
          int qq; 
          cin >> qq; // Whatever sorcery this is 
          return 0; 
      } 
      

      :sが解決策を考えます指数関数的に増加する配列length

    ハッピー学習!

  • +0

    ちょっと、私のクラスはC++からmatlabに、1学期にはPythonになりました。 qqはin/outputsでウィンドウを保持するだけで、私はそれを見ることができます。 –

    関連する問題