2017-11-30 23 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. 동적으로 새로운 배열에 다시 할당되지 않습니다 값이 할당되지 않습니다 of 다른 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

    어쨌든 고마워요. 코딩 (내 수업은 1 학기에 파이썬에 C + +에서 matlab에 갔다)와 함께 장소에 비트되었습니다. qq는 in/outputs가있는 창을 잡아서 볼 수 있습니다. –